gpt4 book ai didi

javascript - 获取最近类(class)的id值

转载 作者:太空宇宙 更新时间:2023-11-04 14:31:31 25 4
gpt4 key购买 nike

我有一个 div 表,想获取我单击位置左侧的类 live-mu-table-tdq 的 id 值。我认为下面的代码可以工作,但没有。

 $(this).closest(".live-mu-table-tdq").attr("id");

fiddle

<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)
});

最佳答案

.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)
});

Updated fiddle

关于javascript - 获取最近类(class)的id值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com