如何获得动态创建的ID?

时间:2021-05-09 15:20:45

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 ...

我是使用javascript和ajax的绝对初学者,这就是我现在被困住的原因。我有一个while循环,其中有2个不同的按钮。正如我想象的那样,两者都有效,除了一件小事......

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?

product-id始终仅针对第一个元素传递,或者如果我为最后一个元素更改它。如何将正确的产品ID传递给脚本?

This is my PHP file:

这是我的PHP文件:

<?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:

我的Javascript是:

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?

我知道我的示例中的产品ID总是相同的,但如果循环中有10个或更多条目,我怎样才能将正确的产品ID传递给脚本?

2 个解决方案

#1


3  

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

您的问题是id是唯一的,只能分配给一个元素,如下所示:

<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:

您可以使用$(this)来访问当前单击的类,如下所示:

$('.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.

您的解决方案需要向按钮添加onclick()方法。然后获取parent()表单。然后,您可以查找()类并从表单数据中获取val()。

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.

这是一个只是重新添加AJAX请求的工作示例。

$(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:

您的AJAX数据将如下所示:

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代码可能如下所示:

<?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; ?>

#2


0  

I read your code , You want to have multiple entries and want to read / fetch dynamically generated Form's Feilds in the common JS Function Add which is currently referring to FIRST FOUND ELEMENT IN RENDERED HTML - Thats the reason you are getting the same value each time.

我读了你的代码,你想拥有多个条目,并且希望在常见的JS函数Add中读取/获取动态生成的Form的Feilds,这个函数目前是指在渲染的HTML中的第一个已发现的元素 - 这就是你每次获得相同值的原因。

You need to alter the logic with little tric - Pass something uniqueness in argument of ADD function

你需要用很少的三元组改变逻辑 - 在ADD函数的参数中传递一些唯一性

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

NOW read uniquely in ADD Function

现在在ADD函数中唯一读取

function add(post_id){

var userid = document.getElementById(post_id+"_userid").value;
var productid = document.getElementById(post_id+"_productid").value;
var collection = document.getElementById(post_id+"_collection").value;
var wishlist = document.getElementById(post_id+"_wish").value;
### Your code as it is ...  
}

Hope this make you sense How i have generated in Loop Unique ELEMENT ID and pass same ID in the function as Argument to fetch them in JS.

希望这能让你感觉如何在循环唯一元素ID中生成并在函数中传递相同的ID作为Argument以在JS中获取它们。

#1


3  

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

您的问题是id是唯一的,只能分配给一个元素,如下所示:

<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:

您可以使用$(this)来访问当前单击的类,如下所示:

$('.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.

您的解决方案需要向按钮添加onclick()方法。然后获取parent()表单。然后,您可以查找()类并从表单数据中获取val()。

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.

这是一个只是重新添加AJAX请求的工作示例。

$(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:

您的AJAX数据将如下所示:

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代码可能如下所示:

<?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; ?>

#2


0  

I read your code , You want to have multiple entries and want to read / fetch dynamically generated Form's Feilds in the common JS Function Add which is currently referring to FIRST FOUND ELEMENT IN RENDERED HTML - Thats the reason you are getting the same value each time.

我读了你的代码,你想拥有多个条目,并且希望在常见的JS函数Add中读取/获取动态生成的Form的Feilds,这个函数目前是指在渲染的HTML中的第一个已发现的元素 - 这就是你每次获得相同值的原因。

You need to alter the logic with little tric - Pass something uniqueness in argument of ADD function

你需要用很少的三元组改变逻辑 - 在ADD函数的参数中传递一些唯一性

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

NOW read uniquely in ADD Function

现在在ADD函数中唯一读取

function add(post_id){

var userid = document.getElementById(post_id+"_userid").value;
var productid = document.getElementById(post_id+"_productid").value;
var collection = document.getElementById(post_id+"_collection").value;
var wishlist = document.getElementById(post_id+"_wish").value;
### Your code as it is ...  
}

Hope this make you sense How i have generated in Loop Unique ELEMENT ID and pass same ID in the function as Argument to fetch them in JS.

希望这能让你感觉如何在循环唯一元素ID中生成并在函数中传递相同的ID作为Argument以在JS中获取它们。