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条)

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动