javascript - 如何从单击的特定按钮中添加和删除 id?
问题描述
<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>
推荐阅读
- reactjs - 单击上传的图像反应时图像轮播未加载
- android-studio - Android Studio 调试是否与 API 23-26 不兼容?
- android - 尝试从要显示在 ListView 中的字符串列表中读取项目时出错
- mysql - mysql 选择有限制的行,但也包括超过限制的相同投票的用户
- python - Django:切换活跃用户
- java - “选择更新”并使用悲观锁定更新
- python - 将字典行插入数据库
- javascript - 如何使用“。”从 javascript 访问 html 中的字典值 操作员?
- python - 在 for 循环理解中分配默认值以及设置交集
- node.js - 子类函数的返回类型