jQuery通过类搜索获取元素的id

这是我的 HTML
<div id="my_Box_one" class="head-div">
   <div>
       <div class="some_Box">a</div>
       <div class="some_Box">b</div>
    </div>
</div>

我想使用该div的类(“.head-div”)获取父div(“#my_Box_one”)的ID

$(document).ready(function(){

$(".some_Box").click(function(){
   var abc = $(this).parentsUntil(".head-div").attr("id");
   // also tried $(this).parent(".head-div") -- same effect
   alert(abc); // Shows as Undefined
});   

});

我可以做以下事情,它会工作正常,但似乎不对.

var abc = $(this).parent("div").parent("div").attr("id");

解决方法

您可以使用.closest(selector),例如:
var abc = $(this).closest(".head-div").attr("id");

http://api.jquery.com/closest/

.parent(selector)仅选择元素的直接父级.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...