2016-11-07 61 views
-1

我試圖讓按鈕被點擊的父div內的一些div的文本。這是一個示例代碼如何獲得接近按鈕點div的文本

​​

這裏parentDiv重複夫婦divToFind的時間和文本是在每個parentDiv不同。每當在parentDiv中點擊刪除按鈕時,我想獲取divToFind的文本。

我已經試過這

$(this).closest('.parentDiv').children('#divToFind').text(); 

但沒有什麼是返回

+3

請勿在單個文檔中使用兩個相同的ID。 –

+0

有趣的人給-1沒有告訴爲什麼。是因爲有問題還是因爲他們不喜歡你犯了錯誤。如果是後者則是擊敗了整個stackoverflow的目的。就像不鼓勵一個人提問一樣。 – jas

+0

@jss澄清,我沒有**給你-1。我認爲這個問題很好。 –

回答

2

不要在單個文檔中使用相同的ID。你應該使用類來代替。隨着課堂,它工作正常。

在中提到,文檔中不能有多個元素具有相同的id值。

$(function(){ 
 
    $("button").on("click", function(){ 
 
    var t = $(this).closest('.parentDiv').children('.divToFind').text(); 
 
    console.log(t); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="parentDiv" > 
 
    <div class="divToFind" style="display:none">text</div> 
 
    <div class="btn-group"> 
 
     <button class="button" type="button" >Remove</button> 
 
    </div> 
 
</div>     
 
<div class="parentDiv" > 
 
    <div class="divToFind" style="display:none">text2</div> 
 
    <div class="btn-group"> 
 
     <button class="button" type="button">Remove</button> 
 
    </div> 
 
</div>

0

是的,它真的,你不應該使用相同的ID爲HTML文檔中的2個元素,但是下面是代碼,可以幫助你得到給出的div的文本。

有2種方式:

$(this).parent().prev('#divToFind').text(); 

$(this).parent().prev().text(); 

prev和next讓我們穿越在同一水平上。你可以在裏面提供選擇器來獲得特定的元素。

在你的例子中它的ID,你可以更新ID到一些CSS類,這樣你就不必擁有具有相同ID的元素。