您好我有一些看起来像这样的HTML,
<div id="music_interests">
<ul class="interests">
<li >
<div class="interest inline">
<img src=""/>
<div class="interest_popup">
1 users have this interest.
<a href="http://localhost/love/index.php/my_profile/remove_interest/34" class="button red upper rounded_5 small remove">Remove interest</a> </div>
</div>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
当用户单击删除按钮时,我需要选择父div(在本例中为music_interests).我该怎么办呢?
我试过做以下事情,
$(this).parent().parent().parent().parent() 但是有更优雅的方式吗?
为了使事情进一步复杂化,我不会在应用程序中实际没有父母ID,因为删除按钮出现在页面上的4或5个不同区域.
你应该使用 closest()
$(this).closest('div#music_interests');
//find the nearest div with id "music_interests"
//if i omitted the id, it retrieves the div with class "interest_popup"
Run Code Online (Sandbox Code Playgroud)
要么 parents()
$(this).parents('div:eq(1)');
//get ALL the ancestor divs (until it reaches root tag)
//since music_interests is just 2 levels up, use :eq(1)
Run Code Online (Sandbox Code Playgroud)