0

再会!请帮忙,如果在嵌套元素中触发点击事件,我会使用嵌套,调用函数和外部父级。如何为内部发起一次事件?

html

<ul>
    <li><a href="#">Item</a></li>
    <li><a href="#">Item 2</a>
        <ul>
            <li><a href="#">Subitem 1</a></li>
            <li><a href="#">Subitem 2</a></li>
            <li><a href="#">Subitem 3</a></li>
        </ul>
    </li>
</ul>

jQuery

$("ul li").on("click", function(e){
    alert($("a", this).text());
});

代码http://jsfiddle.net/fSkLb/1/

4

6 回答 6

2

Instead of listening on li, you can listen to the a

$("ul li a").on("click", function(e){
    alert($(this).text());
    return false;
});

Also, return false here stops the propogation.

于 2013-04-08T18:16:00.073 回答
2

The easiest way is for you to prevent propagation of the event to the parent elements

http://jsfiddle.net/fSkLb/3/

$("ul li").on("click", function(e){    
    e.stopPropagation();
    alert($("a", this).text());
});

Some of the other answers say to use return false. I wouldn't suggests that unless you're trying to prevent the link from being followed. e.stopPropagation is the way with the least amount of side effects.

于 2013-04-08T18:14:59.283 回答
1

You need to prevents further propagation of the current event. so try this

$("ul li").on("click", function(e){
    alert($("a", this).text());
    e.stopPropagation()
});

JS Fiddle Example

于 2013-04-08T18:16:03.363 回答
0

I think I found the answer...

$("ul li").on("click", function(e){
    e.stopPropagation();
    alert($("a", this).text());
});
于 2013-04-08T18:18:20.660 回答
0

You can use the event's stopPropagation method, which will prevent the event from bubbling up the DOM tree:

$("ul li").on("click", function(e){
    e.stopPropagation();
    alert($("a", this).text());
});

Here's an updated jsfiddle: http://jsfiddle.net/fSkLb/5/

于 2013-04-08T18:15:23.897 回答
0
$("ul li").on("click", function(e){
    alert($("a", this).text());
    return false;
});

return false avoids event bubble. The same can be done with stopPropagation.

于 2013-04-08T18:15:44.177 回答