我有一个div表,想要获取我点击的左侧的类live-mu-table-tdq
的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)
});
答案 0 :(得分:3)
.live-mu-table-tdq
元素是live-mu-table-tda
元素的兄弟元素,因此您需要使用siblings()
,而不是closest()
:
$(".live-mu-table-tda").click(function() {
var abc = $(this).siblings(".live-mu-table-tdq").prop("id");
alert(abc)
});
答案 1 :(得分:2)
.closest()
在DOM中向上看。我相信.siblings(".live-mu-table-tdq").attr("id")
就是你的目标
答案 2 :(得分:1)
你可以尝试.next或.find
$(this).next(".live-mu-table-tdq").attr("id");
$(this).find(".live-mu-table-tdq").attr("id");