简体   繁体   中英

Finding closest element value jquery

<table>
    <tr><td>
        <div><img src="1.jpg">text<span class="get">aa</span> <span class="click">Get value</span></div></div></td></tr>
    <tr><td>
        <div><img src="2.jpg">text<span class="get">bb</span> <span class="click">Get value</span></div></td></tr>
    <tr><td><div><img src="1.jpg">text<span class="get">cc</span> <span class="click">Get value</span></div></div>
        </td></tr>
</table>

How do i get closest value of class get when class click is clicked?

$('.click').click(function() {
    $(this).each(function() {
        $('#sample').text($(document).closest('div').find('.get').text());
    });
});

this not working, it return empty..

Any idea why?

$('.click').click(function() {
  $('#sample').text($(this).siblings('.get').text());
});

Here is working sample: http://jsfiddle.net/rcXka/

In the markup you demonstrated, this should do what you want:

$('.click').click(function() {
    $('#sample').text($(this).siblings('.get').text());
});

Note that if there are multiple siblings with the class of get , this may not do what you want. It'll return the first sibling with that class, rather than the "closest" in the markup -- you'll need to come up with a more strict definition of "closest" if there will be multiple siblings .get s.

Also,

$(this).each(function(){ ... });

Is a meaningless statement. That means "execute this function once for each element in the set of matched elements", but there's only one element in the set of matched elements, namely $(this) . You can replace it with just the contents of the anonymous function.

The .closest() function returns the first parent element that matches the specific selector. So it doesn't make sense to call $(document).closet() -- document has no parents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM