获取最近的类的id值

时间:2016-01-26 12:39:59

标签: javascript jquery html css

我有一个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)   
});

3 个答案:

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

Updated fiddle

答案 1 :(得分:2)

.closest()在DOM中向上看。我相信.siblings(".live-mu-table-tdq").attr("id")就是你的目标

https://api.jquery.com/siblings/

答案 2 :(得分:1)

你可以尝试.next或.find

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