jquery select parent elements sibling

2019-09-02 20:33发布

问题:

Ok, lets see if I can explain this clearly enough here. My HTML looks like

<li>
    <div class="info_left" rel="snack">Fries</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>
<li>
    <div class="info_left" rel="lunch">Burger</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>
<li>
    <div class="info_left" rel="4thmeal">Taco</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>

If you will note you will see a "Remove" and "Favorite" inside a div "info_right". What I need to do when either one of those 2 options is clicked on is get the rel and text values of the same li's "info_left" div. I've tried a few ways but don't think I'm nailing the combo between parent(s), siblings correctly or I dunno. Either way hoping someone can toss me a bone.

回答1:

It should just be:

$('.info_remove,.info_favorite').on('click', function() {
   var $left = $(this).parent().siblings('.info_left');
   var rel = $left.attr('rel');
   var txt = $left.text();
   ...
});


回答2:

jsFiddle example

$(document).ready(function(){
    $(".info_right span").click(function(){
        $("#msg").html($(this).attr("class")+": "+$(this).parent().prev().attr("rel"));
    })
})


回答3:

try this

$('.info_remove,.info_favorite').click(function() {
   var target_elem = $(this).parent().prev();
   alert(target_elem.attr('rel'));
   alert(target_elem.text());
});

fiddle : http://jsfiddle.net/ss37P/1/