jQuery 获取此 DIV 的父 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15312567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Parent ID of this DIV
提问by ldmo
I am looking to find the parent div id (i.e. "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'.
但这只是返回“未定义”。
回答by cosmin.danisor
$(this).closest('div').attr('id')
I think this is what you want
我想这就是你想要的
回答by Tom Walters
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()
对它的任何属性使用 ,如下所示:
$(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()
功能。
回答by Ryan Dunphy
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>
回答by Peeyush
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(document).ready(function($){
$("button").on('click',function(){
alert($(this).closest('div').attr('id'));
});
});
here is the fiddle http://jsfiddle.net/cpeeyush/ydk4e/
回答by mkubilayk
Try this:
尝试这个:
$(this).parent().attr("id");
回答by Ryan O'Neill
Try this:
尝试这个:
$(this).closest('div[id]')
$(this).closest('div[id]')
回答by kroppy
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 是您想要获得的父母