jquery通过他们的孩子li获得父li的文本

时间:2013-12-20 13:53:42

标签: javascript jquery html

当我点击“商品”链接“限制”,“打开”时我怎么能得到“商品”,当我点击“服务”链接“限制”,“打开”时,如何获得“服务” ,提前谢谢

JavaScript的:

$('.goodsLink li a').click(function(){

    alert( $('#nav li ul li  a').html());
    return false;
}); 

HTML:

<ul id="nav">
    <li><a href="#">Create a New Tender</a>

        <ul>
            <li><a href="#"><strong>+</strong> Goods</a>

                <ul>
                    <li><a href="#"><strong>-</strong>&nbspSingle</a>

                        <ul class="goodsLink">
                            <li><a href="link.html"> -   Restricted</a>
                            </li>
                            <li><a href="link2.html"> -   Open</a>
                            </li>
                        </ul>
                    </li>
                    <li><a href="#"><strong>-</strong>&nbspFramework</a>

                        <ul class="goodsLink">
                            <li><a href="link3.html"> -   Restricted</a>
                            </li>
                            <li><a href="link4.html"> -   Open</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href="#"><strong>+</strong> Services</a>

                <ul>
                    <li><a href="#"><strong>-</strong>&nbspSingle</a>

                        <ul class="servicesLink">
                            <li><a href="link5.html"> -   Restricted</a>
                            </li>
                            <li><a href="link6.html"> -   Open</a>
                            </li>
                        </ul>
                    </li>
                    <li><a href="#"><strong>-</strong>&nbspFramework</a>

                        <ul class="servicesLink">
                            <li><a href="link7.html"> -   Restricted</a>
                            </li>
                            <li><a href="link8.html"> -   Open</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

$('.goodsLink li a').click(function() {
    alert( $(this).parents('li:contains("+")').children("a:first").text());
    return false;
});

但最好的方法应该是使用类或致敬来更好地识别您想要查找的元素。这样你就可以用:contains("+")

来代替.topParent

她这个例子:

example with contains

example with class