我应该如何获取一个动态创建的ID?

3

我是javascript和ajax的绝对初学者,这就是为什么我现在被卡住了。我的while循环中有2个不同的按钮,都能正常工作,只有一个小问题...

product-id总是仅针对第一个元素或者如果我更改为最后一个元素而传递。

如何将正确的产品ID传递给脚本呢?

这是我的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; ?>

我的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>

我知道在我的例子中产品id始终相同,但如果循环中有10个或更多条目,我如何将正确的产品id传递到脚本中?


1
一个id必须是唯一的。现在您有几个具有相同id“productid”的元素。您可以将计数器添加到id(“productid2”)中,并将其添加到函数调用onsubmit="return add(2);">中,其中'2'将是计数器/索引。 - Jeff
更好的方法是在 form.submit 上设置事件处理程序,然后使用传入的元素(表单)来获取子元素及其值。 - Jeff
2个回答

3

您的问题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>

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

$('.paragraph').click(function() {
    $(this).html('See, totally legal.');
});

查看此示例以查看其使用方法。


你的解决方案需要为button添加一个onclick()方法。这将获得parent()表单。然后,您可以使用find()查找类并从表单数据中获取val()

您的表单还在提交操作。您需要拥有一个类型为button<button>,以便它不会提交操作。如果您正在多次创建它们,则这也必须是一个类,因为它不会是唯一的。

以下是一个工作示例,只需重新添加您的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>


您的AJAX数据将如下所示:

data: {
    user_id: elements.userid,
    product_id: elements.productid,
    collection_id: elements.collection,
    wishlist_id: elements.wish
}

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

非常感谢!我认为我还有很多要学习的。整个示例现在帮助我更好地理解它了。我试图给出唯一的ID,但是循环中的最后一个条目总是被使用。 - Stefan Klein
没关系。最容易记住的方法是:如果有多个元素:使用类。如果只有一个元素:使用ID。我将在此问题底部添加您需要的PHP代码,见图5。 - Jaquarh
我更新了答案,提供了你的PHP代码。@StefanKlein - Jaquarh
哦,那不是必要的。我成功地整合了你的建议。非常感谢@Jaquarh,现在一切都正常工作。 - Stefan Klein
太棒了。很高兴能帮忙。 - Jaquarh

1

我看了你的代码,你想要多个条目,并且想要在通用JS函数Add中读取/获取动态生成的表单字段,该函数当前引用呈现HTML中的第一个找到的元素 - 这就是你每次都得到相同值的原因。

你需要用一些小技巧改变逻辑 - 在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">

现在在 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 ...  
}

希望这让你明白我如何在循环中生成唯一的元素ID,并将相同的ID作为参数传递给函数以在JS中获取它们。

这与我最初尝试的类似,但我失败了。问题已经得到解决,感谢@Jaquarh。但还是感谢你的努力! - Stefan Klein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接