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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog