2016-01-26 39 views
2

我有一個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) 
}); 
+1

'.closest'搜索_up_在DOM,尋找祖先。 – CBroe

回答

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

你可以嘗試。接下來或.find

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