开发者

Get Id from parent

开发者 https://www.devze.com 2023-03-13 01:09 出处:网络
<div rownumber=\"0\" messageid=\"112\" class=\"post\" style=\"position: relative; top: 0px;\"> <div class=\"post_body\">hey hey hey</div>
<div rownumber="0" messageid="112" class="post" style="position: relative; top: 0px;">
    <div class="post_body">hey hey hey</div>
    <div class="post_info" style="top: 0px;">
        <ul>
            <li class="vote"><a href="#">vote up</a></li>
            <li class="flag"><a href="#">flag</a></li>
        </ul>
    </开发者_如何学Cdiv>
</div>

When I click on the 'vote up' or 'flag' href links, I want to be able to grab the messageId from the main containing div element. How would I do that?


$( 'li.vote a, li.flag a' ).click( function( e )
{
    var msgId = $( this ).closest( 'div.post' ).attr( 'messageid' );

    e.preventDefault();
} );

Demo: http://jsfiddle.net/JAAulde/jQuGP/4/

Using a data- attribute and the jQuery .data() method would be best, though, as it would comply more closely with HTML standards: http://jsfiddle.net/JAAulde/jQuGP/5/


Use closest

$('.post a').click( function() {
    var msgId = $(this).closest('.post').attr('messageid');
});

Also, you should use the data- prefix on custom attributes to ensure conformity with web standards.


You can use .closest() to go up in the tree until a match is found. It is better suited here than .parents() which will filter all the parents of the link (which can be a lot of elements in a bigger markup), while .closest() stops when a match is found.

$('li.vote a, li.flag a').click(function () {
    var id=$(this).closest('div.post').attr('messageid');
});

Another important thing:

For storing arbitrary data on HTML elements, you should use the data- attributes (which were introduced in the HTML5 standard).

So in your example the HTML would be:

<div data-rownumber="0" data-messageid="112" class="post"...

Another advantage (besides a valid HTML document) is that you can simply get these data with the jQuery .data() function:

var id=$(this).closest('div.post').data('messageid');

jsFiddle Demo with data- attributes


This is untested, but something like this may work:

$(".vote a").click(function() {
    var value = $(this).parents(".post").attr("messageid");

    alert(value);
});


Can you get around the problem by dynamically output an id on the <a> element that contains the message id?

something like

<a href="#" id="message-123">


$( 'li.vote, li.flag' ).click(function() {
    var msgId = $(this).closest('[messageId]').attr('messageId');
)}
0

精彩评论

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