我有一個div表,並希望獲得類型live-mu-table-tdq
的id值,它位於我點擊的左側。我認爲下面的代碼可以工作,但沒有。獲取最接近的類別的id值
$(this).closest(".live-mu-table-tdq").attr("id");
<div class="live-mu-table" >
<div class="live-mu-tablee-tr">
<div class="live-mu-table-tdq" id="q-1">q1 goes here</div>
<div class="live-mu-table-tdspacer1"></div>
<div class="live-mu-table-tda" id="a-3"> 3 the answer</div>
</div>
<div class="live-mu-tablee-tr">
<div class="live-mu-table-tdq" id="q-2">q2 question</div>
<div class="live-mu-table-tdspacer1"></div>
<div class="live-mu-table-tda" id="a-1">answer 1</div>
</div>
<div class="live-mu-tablee-tr">
<div class="live-mu-table-tdq" id="q-3">question 3</div>
<div class="live-mu-table-tdspacer1"></div>
<div class="live-mu-table-tda" id="a-2">the answer 2</div>
</div>
</div>
$(".live-mu-table-tda").click(function() {
var abc = $(this).closest(".live-mu-table-tdq").attr("id");
alert (abc)
});
'.closest'搜索_up_在DOM,尋找祖先。 – CBroe