jquery select parent elements sibling

≡放荡痞女 提交于 2019-12-25 08:27:53

问题


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/



来源:https://stackoverflow.com/questions/9043969/jquery-select-parent-elements-sibling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!