[英]Click Event Doesn't Fire After Clicking On/Off One Time
我在使用按钮时遇到了麻烦,单击该按钮会激活弹出菜单。 弹出菜单后,如果再次单击该按钮,则弹出窗口消失。 但是,如果您重新单击该按钮,则在我单击按钮之外的某个位置之前,菜单不会显示。 我认为问题在于单击事件以及将事件绑定到的“ html”选择器。 有任何想法吗?
GetDropDownButton: function (option, thisId) {
var menu = $('#' + option);
// shows the popup
menu.show();
setTimeout(function () {
// idea is to click anywhere to allow popup to close
$('html').one('click', function () {
// hides the popup
menu.hide();
});
}, 100);
},
我认为您在遇到javascript事件冒泡效果时遇到了问题。 当您单击一个按钮时,将首先触发他的click事件,然后触发其父事件,直到DOM一直到文档根目录。 我认为您的解决方案可能是应用jQuery的stopPropagation函数。 我在这里设置了一个小示例: http : //jsfiddle.net/FF73h/
由于代码太少,我也将其粘贴在这里:HTML
<div class="popup">
popup!
</div>
<button class="btn-toggle">on/off</button>
JS
// make the button show/hide the popup
$('.btn-toggle').click(function(e) {
$('.popup').toggle();
// prevent the handler for the document to be called as well, wich would hide again
e.stopPropagation();
});
// make the popup close when clicked anywhere in the document
$(document).click(function() {
$('.popup').hide();
});
// optional: prevent the popup from closing when clicked inside it, stops the ducoment event from beeing called
$('.popup').click(function(e) {
e.stopPropagation();
});
我认为代码应该自我解释。 如果没有,请随时告诉我。
您是否尝试过使用body
而不是html
?
$('body').one('click', function () {
// hides the popup
menu.hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.