开发者

Clicking on a <li> object and excluding tags under it [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How to ignore click event when clicked on children.

I wanted to know how can i build <li> that is clickable with jQuery while inside it, I have <a href="/home"> that i don't want it to do the same as the click on the rest of the li do...

Example :

<li>
    <div> bla bla </div>
    开发者_运维知识库<div> <a href="/home"> </a> </div>
</li>

and the jQuery code :

$(document).ready(function () {
    $('li').hide();

    $("li").toggle(
        function () {
            $(this).next().show("slow");
        },
        function () {
            $(this).next().hide();
        }
    );
});

Now i want the toggle function not to work on the <a href> only on the rest of the <li>, I explain, when I click on the link I want to reach "/home"...

Thanks, Golan


The problem comes from the fact the click event happens on the a tag then bubbles up to happen on the list item, and any other elements that happen to be in that branch of the DOM.

The solution is to stop this bubbling in the click event on the link. Something like the following should work.

$('li a').click(
    function(event){
        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();    
    }
);

You could just return false in the event above, but that would also stop the browser following the link.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜