所以我正在研究这个简单的脚本,当你点击它外部时,它应该隐藏任何对象。
这是jsFiddle和我的简单代码:
HTML
<div class="container">
Click anywhere in this div
<div style="border:1px solid blue; float:right;">div should still open/close</div>
</div>
<div class="close_me">Close me!</div>
JS
$(".container").click(function(){
$(".close_me").toggle();
});
helper_close(".close_me", ".container");
//this is simplified example of my function
function helper_close(target, avoid){
//note that this function will be called once per object
//so it should be fine to bind new event on document
$(document).on("click", function(event){
if( $(event.target).is(avoid) )
return true;
$(target).hide();
});
}
现在您可以看到它有效,(有点)问题是,close_me
当您单击 内部的任何位置时container
,它也应该出现/消失,正如您所看到的,这现在不会发生。
我知道我可以指定每个我想“避免”的对象,但是如果我在那个容器中有 20 个 div 怎么办?那么代码看起来很丑陋......所以我需要一些更好的方法来做到这一点。