0

So I have an H3 that has a grey background rectangle. When you click anywhere in that grey background, a particular div performs a slideToggle(). This works fine.

Now, Inside that H3 I also have a link that calls a jquery function that does something. That works fine too.

But my issue is this, since the link is inside the H3, after its functions executes, it also executes the slideToggle() because I clicked somewhere inside the H3.

So the question becomes, How do I prevent the slideToggle() from happening when I click on the link. I imagine I can use a flag but I'm hoping there is a more elegant way.

Any help would be appreciated.

The HTML code

<h3 id="data_id"> 
    <a href="#" id="random_id" >Random</a>   
</h3>

<div id="data_div_id">
    // The data here is irrelevant to the issue at hand
</div>

The Jquery Code

$('#data_id').click(function() {   
    $('#data_div_id').slideToggle('slow');      
}); 

$('#random_id').click(function(event) {
    // it does something irrelevant to the issue at hand
}); 
4

2 回答 2

3

您可以使用event.stopPropagation()来阻止事件冒泡。

jsFiddle在这里。

$('#data_id').click(function() {   
    $('#data_div_id').slideToggle('slow');      
}); 

$('#random_id').click(function(event) {
    event.stopPropagation();
}); 
于 2013-04-25T15:27:50.353 回答
2

尝试跳过您不希望事件发生的元素:

$('#data_id').click(function(event) {   
    if (event.target !== this)
        return;
    $('#data_div_id').slideToggle('slow');      
}); 

像这样只有#data_id会触发切换,因为你的h3在那个div中,当你点击它们时它也会被执行,但只有一次来自实际点击容器

于 2013-04-25T15:29:22.497 回答