I am looking to find the parent div id (ie "Bakerloo") from this layout when the button is clicked within ".buttonleft0" in jquery / javascript.
<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:
$(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.
Straight up Javascript always works for me.
<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]')
Your code itself have few errors so here is the correct one:
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/
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.