doukuangxiu1621 2018-10-14 19:37
浏览 1115
已采纳

如何获取动态创建的ID?

I'm an absolute beginner in using javascript and ajax and that's why I'm stuck now. I have a while loop in which there are 2 different buttons. Both work, as I imagine, except for one little thing ...

The product-id is always passed only for the first element or, if I change it for the last element. How can I pass the correct product ID to the script?

This is my PHP file:

<?php while ( $product = $browse->fetch( PDO::FETCH_ASSOC ) ) :
    $postid = $product[ 'id' ];
    $userid = 1; ?>

 <div id="content_<?php echo $postid ?>">
 <div id="reload_<?php echo $postid ?>" class="row postfarbe browse">

  <form method='post' action="" onsubmit="return add();">
    <input type="hidden" id="userid" value="<?php echo $userid ?>" class="input-box">
    <input type="hidden" id="productid" value="<?php echo $postid ?>" class="input-box">
    <input type="hidden" id="collection" value="1" class="input-box">
    <input type="hidden" id="wish" value="0" class="input-box">
    <input type="submit" id="submit" value="Add to Collection" class="btn my-2 my-sm-0 btn-outline-dark btn-sm">
  </form>

 </div>
</div>
<?php endwhile; ?>

My Javascript is:

function add()
{
    var userid = document.getElementById("userid").value;
    var productid = document.getElementById("productid").value;
    var collection = document.getElementById("collection").value;
    var wishlist = document.getElementById("wish").value;
    if(userid && productid && collection && wishlist) {
        $.ajax
        ({
            type: 'post',
            url: 'post_collection.php',
            data: {
                user_id:userid,
                product_id:productid,
                collection_id:collection,
                wishlist_id:wishlist
            },
            success: function (response) {
                $("#content_"+ productid).load(" #reload_" + productid);
            }
        });
    }  
    return false;
}
</script>

I know that the product id in my example is always the same, but how can I pass the correct one to the script if there are 10 or more entries in the loop?

  • 写回答

2条回答 默认 最新

  • dongzhuang6177 2018-10-14 20:12
    关注

    Your problem is that id is unique and can only be assigned once to a element, like so:

    <p id="paragraph"> This is legal </p>
    <p id="paragraph"> This is illegal - It is no longer unique </p>
    
    <p class="paragraph"> This is legal </p>
    <p class="paragraph"> This is legal </p>
    

    You can access the currently clicked class by using $(this) like so:

    $('.paragraph').click(function() {
        $(this).html('See, totally legal.');
    });
    

    See this example to see this in use.


    Your solution needs to add an onclick() method to a button. This then gets the parent() form. You can then find() the class and get the val() from the form data.

    Your form was also submitting the action. You need to have a <button> of type button so it does not submit the action. This must also be a class since it will not be unique if you're multiply creating them.

    Here is a working example to just re-add your AJAX request too.

    $(document).ready(function() {
      $('.submit-btn').click(function() {
        var elements = {
          'userid': $(this).parent().find('.userid').val(),
          'productid': $(this).parent().find('.productid').val(),
          'collection': $(this).parent().find('.collection').val(),
          'wish': $(this).parent().find('.wish').val()
        };
    
        console.log("User ID: " + elements.userid);
        console.log("Product ID: " + elements.productid);
        console.log("Collection: " + elements.collection);
        console.log("Wish: " + elements.wish);
    
        // TODO: Add your AJAX request using these elements
      });
    });
    button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
      cursor: pointer;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <!-- This will be generated by PHP -->
    
    <form method='POST'>
      <input hidden class="userid input-box" value="1">
      <input hidden class="productid input-box" value="1">
      <input hidden class="collection input-box" value="1">
      <input hidden class="wish input-box" value="1">
      <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
    </form>
    
    <!-- This will be generated by PHP -->
    <br />
    
    <form method='POST'>
      <input hidden class="userid input-box" value="2">
      <input hidden class="productid input-box" value="2">
      <input hidden class="collection input-box" value="2">
      <input hidden class="wish input-box" value="2">
      <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
    </form>


    Your AJAX Data will look like this:

    data: {
        user_id: elements.userid,
        product_id: elements.productid,
        collection_id: elements.collection,
        wishlist_id: elements.wish
    }
    

    Your PHP code could look like this:

    <?php foreach($browse->fetchAll(PDO::FETCH_ASSOC) as $product):
        $id = $product['id'];
        $productDd = $product['product_id'];
        $productCategory = $product['category']; // TODO: change to your column nanme
        $productWishList = $product['wish']; ?>
    
        <div class="content_<?= $id; ?>">
            <div class="reload_<?= $id; ?> row postfarbe browse">
                <form method='POST'>
                    <input hidden class="userid input-box" value="<?= $id; ?>">
                    <input hidden class="productid input-box" value="<?= $productCategory; ?>">
                    <input hidden class="collection input-box" value="<?= $productCollection; ?>">
                    <input hidden class="wish input-box" value="<?= $productWishList; ?>">
                    <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
                </form>
            </div>
        </div>
    
    <?php endforeach; ?>
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗
  • ¥15 用matlab写代码
  • ¥30 motoradmin系统的多对多配置
  • ¥15 求组态王串口自定义通信配置方法或代码?
  • ¥15 实验 :UML2.0 结构建模
  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验
  • ¥15 为什么shp文件会有这种小方块?
  • ¥15 ecplise在连接数据库时显示加载驱动成功但是数据库连接失败
  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥15 IDEA中圈复杂度如何具体设置