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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵