I have this markup:
我有这个标记:
<ul><li id="link-notifications">
<ul class="list-notifications" style="display:none">
<li><a href="/link/to">Item 1</a></li>
</ul>
</li>
</ul>
with this Jquery:
用这个Jquery:
$('#link-notifications').click(function(e){
e.preventDefault();
e.stopPropagation();
$(this).find('.list-notifications').slideToggle('medium');
});
but whenever the list slides down, and I click the link, the list just slides back up. I have heard that stopPropagation works so I added it but it does not work. I even tried adding it to the slideToggle callback but it just stops the slideUp action. Any ideas?
但只要列表向下滑动,我点击链接,列表就会向上滑动。我听说stopPropagation有效,所以我添加了它,但它不起作用。我甚至尝试将它添加到slideToggle回调中,但它只是停止了slideUp动作。有任何想法吗?
3 个解决方案
#1
2
Binding click
event only to #link-notifications
ans escaping its inner contents.
仅将点击事件绑定到#link-notifications并转义其内部内容。
$('#link-notifications, :not("#link-notifications > *")').click(function(e){
e.stopPropagation();
$(this).find('.list-notifications').slideToggle('medium');
});
#2
0
You don't need e.stopPropagation()
inside that event but in the click of the link.
你不需要在该事件中使用e.stopPropagation(),而是点击链接。
Just add
$('.list-notifications').click(function(e){
e.stopPropagation();
});
#3
-2
HTML
<ul>
<li id="link-notifications">
<a href="#">link-notifications</a>
<ul class="list-notifications">
<li><a href="#">Item 1</a></li>
</ul>
</li>
</ul>
jQuery
$('#link-notifications>a').click(function(event){
$(this).siblings('ul.list-notifications').slideToggle('medium');
});
I attached the event not to a parent of what I wanted to slide but a sibling. This keeps weird events from bubbling.
我把这个事件不是我想要滑动的父母而是一个兄弟姐妹。这使得奇怪的事件不会冒泡。
#1
2
Binding click
event only to #link-notifications
ans escaping its inner contents.
仅将点击事件绑定到#link-notifications并转义其内部内容。
$('#link-notifications, :not("#link-notifications > *")').click(function(e){
e.stopPropagation();
$(this).find('.list-notifications').slideToggle('medium');
});
#2
0
You don't need e.stopPropagation()
inside that event but in the click of the link.
你不需要在该事件中使用e.stopPropagation(),而是点击链接。
Just add
$('.list-notifications').click(function(e){
e.stopPropagation();
});
#3
-2
HTML
<ul>
<li id="link-notifications">
<a href="#">link-notifications</a>
<ul class="list-notifications">
<li><a href="#">Item 1</a></li>
</ul>
</li>
</ul>
jQuery
$('#link-notifications>a').click(function(event){
$(this).siblings('ul.list-notifications').slideToggle('medium');
});
I attached the event not to a parent of what I wanted to slide but a sibling. This keeps weird events from bubbling.
我把这个事件不是我想要滑动的父母而是一个兄弟姐妹。这使得奇怪的事件不会冒泡。