我在这里使用js/jquery遇到了一些困难:
我有几个不同子元素的父级LIs。现在,每个子元素都有自己的附加事件处理程序。现在我需要的是调用父类的事件(如果它缺少某个类),如果父类有该类,则调用(单击的)子事件:
<div id="parent" class="expanded">
<span class="child1"></span>
<div class="child2"></div>
<font class="child3"></font>
</div>
现在,如果父容器缺少类“展开”,我只想执行每个子事件。如果父函数是“展开的”,我需要允许执行的函数。
现在,在子元素上的每个处理程序中都可以很容易地请求这个类,但是我认为只使用一个处理程序就可以更好地解决这个问题,它决定并阻止事件的发生。你知道什么好的解决办法吗?
找到解决办法:
很容易说,关键是捕捉。由于jQuery不支持捕获(冒泡的另一个方向:从父到子),所以我可以使用这个解决方法
现在,它可以将以下内容添加到代码的开头:
$('#parent').get(0).addEventListener('click', function(e) {
if(!$(this).closest('li').hasClass('expanded')) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return getTicket(e, $(this)).toggleVisibility();
}
}, true);
发布于 2014-05-12 00:21:27
$(".child").click(function(){
if($(this).parent().hasClass("expanded"))
{
//do parent stuff with $(this).parent()
}
else
{
//do child stuff with $(this)
}
});
发布于 2014-05-12 00:41:45
如果已经定义了单独的子事件处理程序;
您可以创建一个通用子事件处理程序,并抛出用户异常(当其父事件未展开时),以防止进一步的子特定事件。
$(".child").on("click", function (e) {
//If parent does not have class expanded
if (!$(this).parent().hasClass("expanded"))
throw {}
});
/* Child handlers already defined */
$("span.child").on("click", function (e) {
console.log('span');
});
$("div.child").on("click", function (e) {
console.log('div');
});
/**/
发布于 2014-05-12 00:52:45
或者,您可以使用.parent().not() api来实现您的目标;如下所示:
$(".child").parent().not(".expanded").click(function(){
// code to parent which is not having class expanded should go here.
}
https://stackoverflow.com/questions/23603992
复制