jQuery - Click on LI, show/hide UL - Click on LI:a href, continue to show UL and open in Blank Window

亡梦爱人 提交于 2019-12-03 22:16:08

I think what you are looking for is probably event.stopPropagation()

Here's the documentation: http://api.jquery.com/event.stopPropagation/

Basically, what's happening is that when you click on the <a>, the click event is triggering, but since it is contained in the <li> the click event is also triggered on it. This process of the event going from child to parent is called event bubbling. You can use event.stopPropagation() to stop it.

Let's assume you have an HTML structure like so:

<ul>
    <li class="reveal">One<br />
        <a href="http://www.google.com" target="_blank">Google</a>
            <ul>
                <li>a</li>
                <li>b</li>
                <li>c</li>
        </ul>
    </li>
    <li class="reveal">Two<br />
        <a href="http://www.google.com" target="_blank">Google</a>
            <ul>
                <li>a</li>
                <li>b</li>
                <li>c</li>
        </ul>
    </li>
    <li class="reveal">Three<br />
        <a href="http://www.google.com" target="_blank">Google</a>
            <ul>
                <li>a</li>
                <li>b</li>
                <li>c</li>
        </ul>
    </li>
</ul>

Further, we'll say that you have a CSS rule:

ul ul { display: none; }

Apply this jQuery, and you should get the result you're looking for:

$(function () {
    $('.reveal').click(function() {
        $(this).children('ul').slideToggle();
    });

    $('.reveal a').click(function(event) {
        event.stopPropagation();
    });
});

Here's a live demo of this in action: http://jsfiddle.net/PaxTg/

you might want to have a look at event orders and then stop propagation of your event at the right time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!