我正在尝试在单击页面上的某个按钮后添加jQuery单击侦听器。单击按钮后,单击页面上的任意位置,脚本将运行。问题是处理程序在您单击按钮后立即运行,并且不等待“正文”单击。这是代码:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<button data-stat="off" onclick="handler(this);">Click here</button>
</body>
<script>
function handler(btn){
if ($(btn).attr("data-stat")=="on"){
$(btn).attr("data-stat", "off");
console.log("A");
}
else {
$(btn).attr("data-stat", "on");
$(document).on("click", function (event) {
console.log("body clicked!");
$(this).unbind();
});
}
}
</script>
</html>
答案 0 :(得分:1)
我认为你应该添加超时以在当前事件循环之后追加监听器:
function handler(btn){
if ($(btn).attr("data-stat")=="on"){
$(btn).attr("data-stat", "off");
console.log("A");
}
else {
$(btn).attr("data-stat", "on");
// add after 1 ms
setTimeout(function() {
$(document).on("click", function (event) {
console.log("body clicked!");
$(this).unbind();
});
}, 1);
}
}
答案 1 :(得分:1)
事件正在冒泡DOM,因此当您将新的事件处理程序附加到父元素时,它将立即调用。有一种名为stopPropagation()
的方法可以阻止事件冒泡。只需将其添加到handler()
方法中即可。
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<button data-stat="off" onclick="handler(this, event);">Click here</button>
</body>
<script>
function handler(btn, ev){
ev.stopPropagation();
if ($(btn).attr("data-stat")=="on"){
$(btn).attr("data-stat", "off");
console.log("A");
}
else {
$(btn).attr("data-stat", "on");
$(document).on("click", function (event) {
console.log("body clicked!");
$(this).unbind();
});
}
}
</script>
</html>