gpt4 book ai didi

javascript - 如何从单击的特定按钮中添加和删除 id?

转载 作者:行者123 更新时间:2023-12-02 22:21:04 25 4
gpt4 key购买 nike

    <script>
$(document).ready(function() {

$("button").on('click', function(argument) {
$("button").attr('id', 'addtocart');
var product_id = $("#product_id").val();
if (product_id!="") {
$.ajax({
type : "POST",
url : "manage-cart.php",
data : 'product_id='+product_id,
success : function (response) {
// action to be performed if successful
$('#addtocart').removeAttr('id');
}
})

}

})
});
</script>

    <div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="5">
<div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="6">
<div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="7">
<div class="buttons">
<button type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="8">

这是我正在使用的脚本和 HTML 代码。单击按钮时,id 会添加到所有按钮,但这不是我希望 id 仅添加到单击的按钮并在执行 ajax 脚本后删除的想法。

最佳答案

您需要使用$(this)

 $(document).ready(function() {

$("button").on('click', function(argument) {
var _t = $(this);
_t.attr('id', 'addtocart');
var product_id = $("#product_id").val();
if (product_id!="") {
$.ajax({
type : "POST",
url : "manage-cart.php",
data : 'product_id='+product_id,
success : function (response) {
// action to be performed if successful
_t.removeAttr('id');
}
})

}

})
});
</script>

关于javascript - 如何从单击的特定按钮中添加和删除 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com