给出以下简单的 html:
<div class="someContainer">
<h5>Some other information</h5>
</div>
以及以下主干视图:
var view = Backbone.View.extend({
events: {
'click .someContainer': performAction
},
performAction: function (evt) {
// Do things here
}
});
我发现自己经常执行以下代码,这对我来说似乎有点代码味道。我做错了什么或者有更好的方法吗?
...performAction: function (evt) {
// Check to see if the evt.target that was clicked is the container and not the h5 (child)
if ($(evt.target).hasClass('someContainer')) {
// Everything is ok, the evt.target is the container
} else {
// the evt.target is NOT the container but the child element so...
var $container = $(evt.target).parent('.someContainer');
// At this point I now have the correct element I am looking for
}
}
显然,这是可行的,但我不确定这是否是适合在任何地方编写的好代码。我可以创建一个可以直接调用的方法,但我不确定是否真的可以纠正代码味道,它只是将其外包到其他地方。
你可以使用evt.currentTarget http://api.jquery.com/event.currentTarget/反而:
事件冒泡阶段中的当前 DOM 元素。
Demo: http://jsfiddle.net/ambiguously/UgA5M/ http://jsfiddle.net/ambiguous/UgA5M/
或者你可以使用$container = $(evt.target).closest('.someContainer')
不用担心嵌套。
Demo: http://jsfiddle.net/ambiguously/B49LG/ http://jsfiddle.net/ambiguous/B49LG/
您使用哪种方法取决于您的具体情况。如果您在某种控件上有一个单击处理程序,那么closest
可能更有意义;如果您确实想要将点击处理程序绑定到的元素(或者认为您拥有,这一切都是基于delegate https://stackoverflow.com/a/7802255/479863毕竟),然后使用currentTarget
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)