javascript按钮单击功能不工作
我有一个网站,用户可以选择一个项目,然后显示详细信息,包括数量。我还包括一个按钮内的div,以便当点击,它应该减少1数量javascript按钮单击功能不工作,javascript,jquery,function,click,Javascript,Jquery,Function,Click,我有一个网站,用户可以选择一个项目,然后显示详细信息,包括数量。我还包括一个按钮内的div,以便当点击,它应该减少1数量 $("#btnBuy1").click(function() { if (!sessionStorage['quantity1']) { sessionStorage['quantity1']=1; } else
$("#btnBuy1").click(function()
{
if (!sessionStorage['quantity1'])
{
sessionStorage['quantity1']=1;
}
else
{
sessionStorage['quantity1']++;
}
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
updateBasket();
sessionStorage["total1"] = parseInt(sessionStorage.getItem('quantity1')) * teddy[1].price;
updateSubtotal();
if (Modernizr.sessionstorage)
{ // check if the browser supports sessionStorage
myids.push(teddy[1].partnum); // add the current username to the myids array
sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
}
else
{
// use cookies instead of sessionStorage
}
});
$("#btnRemove1").click(function()
{
alert(remove);
});
我输入了一条警告消息,以查看按钮是否正常工作,但当我单击btnRemove1按钮时,什么也没有发生。由于按钮是动态添加的,您可以尝试:
$(document).on('click', '#btnRemove1', function() {
{
alert("remove"); //I dont know what remove was is the example, added quotes around it.
});
创建移除按钮后,尝试放置移除按钮单击处理程序添加
///Code snippit
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
$("#btnRemove1").click(function()
{
alert(remove);
});
updateBasket();
///Code snippit
您可以将事件绑定到文档,就像jQueryLive在被弃用之前所做的那样 现在是:
$(document).on("click", "#btnRemove1", function(){})
或者,您可以在将btnRemove1添加到Dom后重新绑定事件。这是因为按钮稍后会动态添加。您必须使用委托 你不必用身体来做这个。作为btnRemove1父级的任何非动态插入元素都可以
$('body').on('click','#btnRemove1',function(){
alert(remove);
});
原因是您在页面上出现元素btnRemove1之前绑定了事件。因此,没有什么可以约束事件。但是,body元素-将出现在页面上,并将您的事件委托给btnRemove1。最有可能的是,在您尝试将单击事件附加到DOM之前,您的移除按钮不在DOM中。很难从代码片段中分辨出来,但是如果Buy按钮操作没有成功完成,那么Remove将不存在 在附加要删除的click事件时,请尝试控制台日志记录$btnRemove1.length以查看它是否存在,或者使用断点 代码的一个改进是缓存在变量$dropbox中,然后在其中查找按钮,如下所示:
var $dropBoxNode = $("#dropbox");
$dropBoxNode.find("#btnRemove1");
您应该使用.on而不是不推荐的。单击
$('a.edit').on('click','a.edit',function(){
if (confirm("Are you sure you want to Edit this Photo?"))
{
....
....
}
});
在DIV区域上使用AJAX加载数据时不工作
就像
<a href="javascript:;;" class="edit">EDIT</a>
你的HTML代码在哪里?您正在使用哪个版本的jQuery?您不应该在这里通知一个字符串吗?警报移除;您可以在创建btnRemove1的位置添加代码吗?btnBuy1 click功能是否按预期工作?@FloatingCoder:按钮添加在$dropbox.html部分。@FloatingCoder是的,buyBtn1工作正常,我在dropbox中显示了详细信息