比如想實現點擊列表彈出篩選器,點擊其他任意地方關閉篩選器,如圖
該篩選器class名
$(document).click(function () { $(".subMenu").hide(); }); $(".subMenu").on("click", function (event) { //取消事件冒泡 var e = arguments.callee.caller.arguments[0] || event; //若省略此句,下面的e改爲event,IE運行可以,但是其他瀏覽器就不兼容 if (e && e.stopPropagation) { // this code is for Mozilla and Opera e.stopPropagation(); } else if (window.event) { // this code is for IE window.event.cancelBubble = true; } });
首先點擊document任意位置隱藏該元素,然後給該元素綁定click事件,阻止冒泡到該元素,則可以順利實現需求。