[英]Get Parent ID of this DIV
當在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>
我努力了:
$(this).parent('id');
但這只會返回“未定義”。
$(this).closest('div').attr('id')
我想這就是你想要的
parent()
函數返回jQuery對象,因此您需要對所有attr()
使用attr()
,如下所示:
$(this).closest().attr('id');
編輯:在進一步檢查中,該按鈕不是div
的直接子級,因此將需要使用closest()
函數。
直接使用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");
嘗試這個:
$(this).closest('div [id]')
您的代碼本身幾乎沒有錯誤,因此這里是正確的錯誤:
的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'));
});
});
alert($(this).parent().id);
如果您要確保選擇正確的課程,請嘗試:
alert($(this).parent('.div').id);
如果您有更深的層次結構,則可以使用:
alert($(this).parents('.div:eq(n)').id);
n是您想得到的父母
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.