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

穿精又带淫゛_ 提交于 2019-12-05 04:58:41

问题


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.



来源:https://stackoverflow.com/questions/3535442/jquery-click-on-li-show-hide-ul-click-on-lia-href-continue-to-show-ul-and

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