2013-05-02 17 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的:

相关问题