当用户点击div之外时,如何在Backbone中隐藏div? [英] How to hide a div in Backbone when user clicks outside of div?
问题描述
我在Backbone中有一个包含内部div的视图。我希望在用户点击div之外时隐藏div。
I have a View in Backbone that contains an inner div. I want to hide the div when the user clicks outside of the div.
我不确定如何在View中设置一个点击NOT的事件#inner_div:removeDiv。
I'm not sure how to set up an Event inside of the View that says "click NOT #inner_div": "removeDiv".
有关如何执行此操作的建议吗?
Any suggestions on how to do this?
推荐答案
通常的方法是将点击处理程序直接附加到< body>
,然后关闭或隐藏< DIV>
。例如:
The usual approach is to attach a click handler directly to <body>
and then have that close or hide your <div>
. For example:
render: function() {
$('body').on('click', this.remove);
this.$el.html('<div id="d"></div>');
return this;
},
remove: function() {
$('body').off('click', this.remove);
// This is what the default `remove` does.
this.$el.remove();
return this;
}
如果你只想隐藏< div> ;
而不是删除它,只需将< body>
上的点击绑定到与 删除
;您仍然希望在删除
中删除< body>
中的点击处理程序。此外,您还希望在视图的 el
中捕获点击事件,以防止他们转到< body>
。
If you just want to hide the <div>
rather than remove it, just bind clicks on <body>
to a different method than remove
; you'll still want to remove the click handler from <body>
in your remove
though. Also, you'll want to trap click events on your view's el
to keep them from getting to <body>
.
演示: http://jsfiddle.net/不明确/ R698h /
如果您有其他关注点击事件的元素,那么您绝对可以定位< div>
掩盖< body>
然后将您的点击处理程序绑定到该处理程序。您可以查看 jQuery BlockUI 插件,了解如何完成此操作。
If you have other elements that care about click events then you could absolutely position a <div>
to cover up the <body>
and then bind your click handler to that. You could have a look at the jQuery BlockUI plugin to see how this is done.
这篇关于当用户点击div之外时,如何在Backbone中隐藏div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!