2013-05-02 42 views
0

也許我搜索得很差,但到目前爲止我還沒有找到我的問題的答案。首先是Javascript函數的代碼:如何獲得一個隱藏的兄弟的div的內容到一個按鈕 - jQuery相關

<script> 
    function showComment(){ 
     var $data = $(this).parent("td").contents("div.hiddenComment").text(); 
     console.log($data); 
     alert($data); 
     return false; 
    } 
</script> 

我還包括了我正在處理的HTML代碼。基本上它是一個<table>,在一個<td>有一個<button>和一個隱藏的<div>。應在警告/對話框中顯示<div>的內容。

<table class="center"> 
     <thead> 
      <tr> 
      <th>Status</th> 
      <th>Datum</th> 
      <th>Zeit</th> 
      <th>Amount</th> 
      <th>Source</th> 
      <th colspan="2">Comment</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
      <td>status1</td> 
      <td>2013-04-04</td> 
      <td>06:30:38</td> 
      <td>3.646.268,00</td> 
      <td>SRC1</td> 
      <td> 
       <div class="hiddenComment">a comment</div> 
       <button name="showComment" type="button" href="#" class="showComment" onClick="showComment()">show</button> 
      </td> 
      <td><a href="#" class="addComment">add</a> 
      </td> 
      </tr> 
      <tr> 
      <td>status</td> 
      <td>2013-04-05</td> 
      <td>06:30:48</td> 
      <td>1.732.213,00</td> 
      <td>SRC2</td> 
      <td> 
       <div class="hiddenComment">an other comment</div> 
       <button name="showComment" type="button" href="#" class="showComment" onClick="showComment()">show</button> 
      </td> 
      <td><a href="#" class="addComment">add</a> 
      </td> 
      </tr> 
      ..... 
     </body> 
</table> 

我想你可以從這段代碼中得到關於<table>的想法。無論如何,我在搜索網絡之後所取得的最好成績是一條"undefined"消息。

我應該注意:類.hiddenComment有CSS屬性display:none

任何提示,技巧和竅門受到熱烈歡迎!

感謝您的時間和幫助。

回答

1

您可以將單擊事件附加到類showComment。從那裏你可以得到以前的元素並獲取它的文本。

Demo

$('.showComment').click(function(){ 
    alert($(this).prev().text()); 
    //or the below if the order of your elements might change. 
    //alert($(this).siblings('.hiddenComment').text()); 
}); 

如果您的內容是動態地加載,你可以使用委託:

$('body').on('click','.showComment',function(){ 
    alert($(this).prev().text()); 
}); 
0

你使用jQuery現在的工作,殺死ol'skool在線點擊通話。簡而言之,以下內容將適用於您現在擁有的內容。刪除內聯 「的onclick」 事件的,並添加到您的JS:

<script> 
    function showComment(event){ 
     var $data = $(this).parent("td").contents("div.hiddenComment").text(); 
     console.log($data); 
     alert($data); 
     return false; 
    } 
    $(function() { 
     $("button[name=showComment]").on("click", showComment); 

     // OR with a different selector, such as a class name 
     // $(".showComment").on("click", showComment); 

     // OR asign it as a delegate, accounting for "dynamic data" 
     // $("td").on("click", "button[name=showComment]", showComment); 
    } 
</script> 

jsFiddle (working example using YOUR code)

瞭解更多關於jQuery的:

相關問題