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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀