jQuery - Click on LI, show/hide UL - Click on LI:a

2019-04-02 06:11发布

问题:

Thanks to the wonderful contributors here at SO! jQuery is much cooler when you begin to understand it. :)

So I have an LI that when clicked shows/hides a child UL. What I would like to do is have the ability to click on an link inside the LI that opens a blank window, but also doesn't close the child UL. The blank window opening is done

a[href^="http://"]').attr("target", "_blank");

however, I am not sure how to "return: false" on the LI so it doesn't close the UL when the blank window opens. I want the user to be able to see the child UL they were on when they close the blank window.

If this is not clear, please let me know.

Thanks!

回答1:

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/



回答2:

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