我正在开发 shopping cart我需要防止在将产品添加到购物车时重新加载页面。
目前我正在使用GET方法将产品提交到购物车
<a href="cart/add?itemid=101&itemcat=starter></a>
如您所见,我使用的是链接标记而不是表单。我试过这段代码来防止页面重新加载
$(document).ready(function(){
$(".prod a").click(function(){
var id = $(".prod").find('input[id=itemid]').val();
var cat = $(".prod").find('input[id=itemcat]').val();
alert('ID :' + id + '\n\rCAT :' + cat);
return false; // reload stopped
});
});
正如您可能已经注意到的,我使用 alert() 来测试输出就像我只得到只有第一个产品的值其余被忽略想到使用 loop 。请验证以上代码或建议其他解决方案。
这是 fiddle * 更新
问题是我能够获得第一个产品的项目 ID 而不是第二个
最佳答案
使用event.preventdefault()停止 anchor 标记的默认行为。
你需要this keyword
改变
var id = $(".prod").find('input[id=itemid]').val();
var cat = $(".prod").find('input[id=itemcat]').val();
到
您需要最接近的 tr
元素而不是 .prod
var id = $(this).closest('tr').find('#itemid').val();
var cat = $(this).closest('tr').find('#itemcat').val();
$(this).closest('tr')
获取 DOM
中最近的 tr
元素。
$(document).ready(function () {
$(".prod a").click(function (e) {
e.PreventDefault(); //to stop default behavior of anchor tag
//this refers to the current a element clicked .
var id = $(this).closest('tr').find('#itemid').val();
var cat = $(this).closest('tr').find('#itemcat').val();
alert('ID :' + id + '\n\rCAT :' + cat);
return false; // reload stopped
});
});
关于javascript - 在将项目提交到购物车时防止页面重新加载。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630272/