Javascript 如何获得div的id,点击按钮,在它里面?
我有多个面板,每个面板都有添加按钮:Javascript 如何获得div的id,点击按钮,在它里面?,javascript,jquery,html,Javascript,Jquery,Html,我有多个面板,每个面板都有添加按钮: <div id="panel1"> <input type="button" id="addbut" value="Add it"></input> </div> <div id="panel2"> <input type="button" id="addbut" value="Add it"></input> </div> <div id="panel3"
<div id="panel1">
<input type="button" id="addbut" value="Add it"></input>
</div>
<div id="panel2">
<input type="button" id="addbut" value="Add it"></input>
</div>
<div id="panel3">
<input type="button" id="addbut" value="Add it"></input>
</div>
单击按钮,我想打印包含此按钮的div的id(或其他属性)。在JQuery中
$("#addbut").click(function(){
alert(ID of panel to which this button belong - this.?) <-- Want to achieve
});
$(“#添加但”)。单击(函数(){
警报(此按钮所属面板的ID-this.?)div是按钮的父节点,因此您可以获取parentNode及其ID
$(“.addbut”)。单击(函数(){
警报(this.parentNode.id);
console.log($(this.parent().attr('id'))
});
像这样做:
$("#addbut").click(function(){
alert($(this).parent().attr('id')) <-- Want to achieve
});
还要注意的是,每个元素都应该有唯一的id
。因此,使用class
来代替class=“addbut”
,代码将是
$(".addbut").click(function(){
alert($(this).closest('div').attr('id')) //OR $(this).parent().attr('id')
});
ID必须是唯一的,因此将ID
更改为class
,如下所示
$(“.addbut”)。单击(函数(){
警报($(this.parent().attr('id'));
//$(此)-指按钮
//$(this).parent()返回父元素
//.attr('id')返回id属性
});
$(“.addbut”)。单击(函数(){
警报($(this.parent().attr('id'));
});
//这是指当前元素
//.parent()返回元素最近的父元素
//可以使用所需元素上的.attr()方法获取任何属性
$(".addbut").click(function(){
alert($(this).closest('div').attr('id')) //OR $(this).parent().attr('id')
});
$(".addbut").click(function(){
alert($(this).parent().attr('id'));
});
// this refers to the current element
// .parent() returns the nearest parent of a element<br>
// you can get any attribute using .attr() method on the required element