Javascript jQuery单击按钮并获取上面最近的id:
我有这个html,当我点击按钮时,我需要在上面的包装器div上获得最近的id 以下是html:Javascript jQuery单击按钮并获取上面最近的id:,javascript,jquery,Javascript,Jquery,我有这个html,当我点击按钮时,我需要在上面的包装器div上获得最近的id 以下是html: <div id="some_id_here" class="wrapper> <div class="panel panel-default"> <div class="panel-heading"> <div class="toolbuttons"> <a class="btn btn-default"&g
<div id="some_id_here" class="wrapper>
<div class="panel panel-default">
<div class="panel-heading">
<div class="toolbuttons">
<a class="btn btn-default">click here and get the id in wrapper</a>
</div>
</div>
</div>
</div>
您可以将最近的与类选择器一起使用,并使用attr
$(函数(){
$('a.btn')。在('click',function()上{
var id=$(this).closest('.wrapper').attr('id');
console.log(id);
});
});代码>
单击此处并在包装器中获取id
您可以这样做:
$('a.btn').click(function() {
var id = $(this).closest("[id]").attr("id");
console.log(id)
});
演示
$('a.btn')。单击(函数(){
var id=$(this.closest(“[id]”)attr(“id”);
控制台日志(id)
});代码>
单击此处并在包装器中获取id
单击此处并在面板标题中获取id
$('.btn')。在('click',function()上{
让wrapperid=$(this).closest('.wrapper').prop('id'))
console.log(wrapperid)
})
单击此处并在包装器中获取id
您可以这样做:
var newid = $(this).closest('div[id]');
$(this).att('id', $newid);
虽然所有答案都是正确的,但您可以使用父类方法和类选择器来查找下面的div.是工作代码
$(document).ready(function(){
$("#btn").on("click",function(){
console.log($(this).parents('.wrapper').attr("id"));
})
});
这里正在使用JS查找最近的id为的父项
函数foo(ele){
变量id=元素最近(“[id]”)id;
控制台日志(id)
}
单击此处并在包装器中获取id
$('btn-default')。单击(函数(){
var id=$(this).closest(.wrapper”).attr(“id”);
控制台日志(id)
});
阅读:。