开发者

Using jQuery to find ID of containing element

开发者 https://www.devze.com 2023-01-09 08:04 出处:网络
<li id=\"someID\"> <div id=\"div1\">Text</div> <div id=\"div2\">Text x 2</div>
<li id="someID">
    <div id="div1">Text</div>
    <div id="div2">Text x 2</div>
    <div id="div3">Text x 3</div>
        <span>
            <div>
                <ul>
                    <li class="menu开发者_如何学PythonItem">Menu Item</li>
                </ul>
            </div>
        </span>
</li>

In short, I'm trying to find the ID "someID" when the class "menuItem" is clicked. The code below doesn't seem to be cutting it.

$('.menuItem').click(function(){alert($(this).closest('li').attr('id'));});


instead of .closest('li'). use the .parents('li'). (note the plural)

It is even mentioned at the closest() documentation ..


Another approach is to put a class on the li you are trying to identify, and make the .closest() selector more precise.

e.g.

<li class="master" id="someID">
    <div id="div1">Text</div>
    <div id="div2">Text x 2</div>
    <div id="div3">Text x 3</div>
        <span>
            <div>
                <ul>
                    <li class="menuItem">Menu Item</li>
                </ul>
            </div>
        </span>
</li>

$('.menuItem').click(function(){alert($(this).closest('li.master').attr('id'));});


If you want the parent then you could use .parent which is documented here


you can use .parent

.parents("li") so it will return the li parent
0

精彩评论

暂无评论...
验证码 换一张
取 消