![](/img/trans.png)
[英]jquery traversing up through parents to find previous element of main parent
[英]Traversing up the DOM in jQuery to grab a parent element
我正在嘗試遍歷 DOM 並從某個子元素(輸入元素)開始獲取某個元素(一個 h2 元素)
這是我的 html :
<div class="main_selector box_1 active">
<h2 class="criterion_title">Course</h2>
<button class="toggle_button" data-contents=".item_1"></button>
<ul class="contents item_1" style="display: block;">
<li>
<input class="courseSelectBox" type="checkbox" id="course_1" value>
<label for="course_1>Brigade S-1<label>
</li>
我的js:
$(document).ready(function(){
$('input:checkbox').click(function(){
console.log($(this).closest("h2").html());
});
});
單擊復選框時,我想獲取最接近的“h2”(criterion_title),並記錄其 HTML。 我得到的只是“未定義”。
你走錯路了
$('input:checkbox').click(function(){
console.log($(this).closest("ul").siblings("h2").html());
});
根據您的 HTML 結構, h2
不是最接近復選框的父元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.