我将点击功能foo
绑定到jquery.ajax
中的锚标记。我面临的问题是我必须请求两次或单击锚标记两次才能发出请求。另外我在网络栏下的浏览器中注意到,当我点击锚标签时,没有触发ajax请求。但当我点击两次然后我在网络选项卡中看到两个ajax请求。我不知道发生了什么事?
<script type="text/javascript">
function show(thelink)
{
var cat = thelink.innerHTML;
var productContainer = document.getElementById("productContainer");
$.ajax({
type:"POST",
url:"fetchdata1",
data:"cat="+cat,
success:function(data){
productContainer.innerHTML ="";
var $productContainer = $('#productContainer');
$.each(data,function(key,value){
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/><a href='#' class='remove' onclick='foo(this)' pid='"+value['id']+"'>REMOVE</a></div>");
}
else{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span></div>");
}
}) ;
}
});
return false;
}
function foo(obj){
var pid = $(obj).attr("pid");
$(obj).bind("click", function(){
$.ajax({
type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,
success:function(response){
console.log("sent ajax request");
}
});
});
}
答案 0 :(得分:0)
您正在将额外的onclick
处理程序绑定到.remove
。
使用动态添加的元素进行回调时,最好使用document
绑定$(document).on("click", 'selector', function(){ ... });
上下文中的所有必需事件。
所以不要a href='#' class='remove' onclick='foo(this)' pid='"+
执行此操作(请参阅下面的代码段)
$(document).on("click", '#productBox .remove', function(){
// your ajax call
$.ajax({
type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,
success:function(response){
console.log("sent ajax request");
}
});
});
这将分离您的HTML布局及其行为。
必须避免下面的事情(感谢@charlietfl):
onclick
属性直接绑定javascript函数。希望它有所帮助。