使用JQuery event.target来处理孩子 [英] Using JQuery event.target to work with children
本文介绍了使用JQuery event.target来处理孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题具体涉及 http://api.jquery.com/event。 target /#example-1
如果您在< li>
中使用跨度,其他标签可以像我所做的那样改变样式,如< b>
这里,元素的那部分将不会触发JQuery函数切换它的孩子。
If you use a span in the <li>
or other tag to change the style such as <b>
as I have done here, that part of the element won't trigger the JQuery function to toggle it's children. How might one go about making this work?
HTML:
<ul>
<li><b>This doesn't work,</b> this does
<ul>
<li>sub item 1-a</li>
<li>sub item 1-b</li>
</ul>
</li>
<li>item 2
<ul>
<li>sub item 2-a</li>
<li>sub item 2-b</li>
</ul>
</li>
</ul>
JavaScript:
JavaScript:
function handler(event) {
var $target = $(event.target);
if( $target.is("li") ) {
$target.children("ul").toggle();
}
}
$("ul").click(handler).find("ul").hide();
推荐答案
为了继续使用您当前的表单,我建议使用 nearest()
:
To keep using your current form, I'd suggest using closest()
:
function handler(event) {
$(event.target).closest('li').children("ul").toggle();
}
$("ul").click(handler).find("ul").hide();
尽管为自己使用,我更愿意:
Though for my own use I'd prefer:
$('li').on('click', function(e){
e.stopPropagation();
$(this).find('ul').toggle();
});
参考文献:
closest()
.on()
.
这篇关于使用JQuery event.target来处理孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文