在不应该的情况下,preventDefault会重复出现在子li中

时间:2013-03-25 10:18:40

标签: jquery html preventdefault

我在下面有以下代码和jsFiddle链接。在我的头脑中我的代码应该工作,它找到正确的li标签并禁用默认操作,问题是它是否会重复进入子元素以及它不应该。你能解开一些亮点吗?

http://jsfiddle.net/andyjh07/6HAvV/

HTML:

<ul id="nav">
    <li class=""><a href="home.htm">Home</a>
    </li>
    <li class="nav_parent"><a href="our-projects.htm">Our Projects</a>
        <ul class="nav_child">
            <li class=""><a href="the-palms-at-corozal.htm">The Palms At Corozal</a>
            </li>
            <li class=""><a href="the-lakes-at-consejo.htm">The Lakes At Consejo</a>
            </li>
        </ul>
    </li>
    <li class="nav_parent"><a href="about-us.htm">About Us</a>
        <ul class="nav_child">
            <li class=""><a href="who-we-are.htm">Who We Are</a>
            </li>
            <li class=""><a href="other-projects.htm">Other Projects</a>
            </li>
            <li class=""><a href="partners.htm">Partners</a>
            </li>
        </ul>
    </li>
    <li class="nav_parent"><a href="about-belize.htm">About Belize</a>
        <ul class="nav_child">
            <li class=""><a href="general-info.htm">General Info</a>
            </li>
            <li class=""><a href="investing-in-belize.htm">Investing In Belize</a>
            </li>
            <li class=""><a href="useful-links.htm">Useful Links</a>
            </li>
        </ul>
    </li>
    <li class=""><a href="news.htm">News Articles</a>
    </li>
    <li class=""><a href="contact-us.htm">Contact Us</a>
    </li>
</ul>

jQuery的:

$(document).ready(function () {
    $('ul#nav li:eq(1)').addClass('removeLink');
    $('.removeLink').click(function (e) {
        e.preventDefault();
    });
});

1 个答案:

答案 0 :(得分:1)

问题在于您绑定了li元素,并且由于子项在li范围内,因此它们也会触发click事件。

尝试更新并阻止仅点击a元素:

$('.removeLink > a').click();

这是一个updated jsFiddle