[英]Get Parent ID of this DIV
I am looking to find the parent div id (ie "Bakerloo") from this layout when the button is clicked within ".buttonleft0" in jquery / javascript. 当在jquery / javascript中的“ .buttonleft0”内单击按钮时,我正在从此布局中查找父div ID(即“ Bakerloo”)。
<div id='Bakerloo' class='box'>bakerloo<p></p><span class='buttons'>
<span class='buttonleft0'><button onClick='up()'><span class='icon icon10'></span>
</button>
</span><span class='buttonleft'></span><span class='buttonright'></span></span>
<div class='comingup'></div>
<div class='more'></div></div>
I have tried: 我努力了:
$(this).parent('id');
But this just returns 'undefined'. 但这只会返回“未定义”。
$(this).closest('div').attr('id')
我想这就是你想要的
The parent()
function returns the jQuery object, so you need to use the attr()
for any of it's attributes like so: parent()
函数返回jQuery对象,因此您需要对所有attr()
使用attr()
,如下所示:
$(this).closest().attr('id');
Edit: On further inspection it appears the button isn't the direct child of the div
, and so use of the closest()
function would be required. 编辑:在进一步检查中,该按钮不是
div
的直接子级,因此将需要使用closest()
函数。
Straight up Javascript always works for me. 直接使用Javascript总是对我有用。
<div id='Bakerloo' class='box'>
bakerloo<p></p>
<span class='buttons'>
<span class='buttonleft0'>
<button onClick='alert(this.parentNode.parentNode.id)'>
<span class='icon icon10'></span>
</button>
</span>
<span class='buttonleft'></span>
<span class='buttonright'></span>
</span>
<div class='comingup'></div>
<div class='more'></div>
</div>
尝试这个:
$(this).parent().attr("id");
Try this: 尝试这个:
$(this).closest('div[id]') $(this).closest('div [id]')
Your code itself have few errors so here is the correct one: 您的代码本身几乎没有错误,因此这里是正确的错误:
HTML 的HTML
<div id='Bakerloo' class='box'>bakerloo<p></p><span class='buttons'>
<span class='buttonleft0'><button><span class='icon icon10'>Click here</span>
</button>
</span><span class='buttonleft'></span><span class='buttonright'></span></span>
<div class='comingup'></div>
<div class='more'></div></div>
JQuery jQuery查询
jQuery(document).ready(function($){
$("button").on('click',function(){
alert($(this).closest('div').attr('id'));
});
});
here is the fiddle http://jsfiddle.net/cpeeyush/ydk4e/ 这是小提琴http://jsfiddle.net/cpeeyush/ydk4e/
alert($(this).parent().id);
If you want to be sure to select correct class, try: 如果您要确保选择正确的课程,请尝试:
alert($(this).parent('.div').id);
If you have a deeper hierarchy you can use: 如果您有更深的层次结构,则可以使用:
alert($(this).parents('.div:eq(n)').id);
where n is which parent you want to get n是您想得到的父母
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.