显示和隐藏另一个表中的表

时间:2013-12-26 16:08:39

标签: jquery html css

我试图在点击一个链接后显示一个表,但只有当链接在表格的一边时它才有效,但是一旦链接在表格内部它就不起作用,我想知道为什么?可能有更好的方法来做到这一点。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>Show and Hide</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">    </script>
<script>
$(function () {

$('.reply-comment').on('click', function (e) {

 e.preventDefault();
 var form = $(this).next('.reply-form');
 var CommentID = $(this).attr('id');

 if (form.is(':visible')) {

   // hide it
   form.hide(function () {

     $('#' + CommentID).html('<a href="" class="reply-comment" id="reply-comment-' + CommentID + '"> Reply </a>');

    });

  }else {

    // show it
    form.show(function () {

      $('#' + CommentID).html('<a href="" class="reply-comment" id="reply-comment-' + CommentID + '"> Cancel </a>');

     });

  }

 });

 });
</script>

<style>
.reply-form {

   display:none;

}
</style>

</head>

<body>
  <div>Start stuff etc etc...</div>
<br />

<table   width="300" border="1" bgcolor="#ffffff" cellpadding="5" cellspacing="0">
<tr>
  <td> Start </td>
  <td> <!-- this will not work, why? -->
    <a href="" id="17" class="reply-comment"> Reply </a>
  </td>
  <td> Out </td>
</tr>
</table>


 <br> <!-- this works, but I can't use like this -->
 <!-- a href="" id="1" class="reply-comment"> Reply </a --> 

 <div class="reply-form well">
 <br />
<table width="300" border="1" bgcolor="#1A1A1A" cellpadding="5" cellspacing="0">
 <tr>
   <td><form name="reply-form" id="repl-form" method="POST">

     <textarea name="Comment" rows="6" class="span10"></textarea>
     <br />
     <br />
     <input type="submit" class="btn btn-primary replycommentsubmitbutton" value="Reply" />

  </td></form>
<tr>
</table>
</div>

<p>&nbsp;</p>
<div>More stuff here etc etc...</div>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

交换这段代码

  

var form = $(this).next('。reply-form');

使用:

  

var form = $('。reply-form');

答案 1 :(得分:0)

问题在于

var form = $(this).next('.reply-form');
jquery中的

next()定义如下:

  

描述:获取每个元素的紧随其后的兄弟   匹配元素的集合。如果提供了选择器,则检索它   只有当它与那个选择器匹配时才是下一个兄弟。

虽然下面的代码不是最佳解决方案,但它适用于特定示例。我会重新编写它以更好地适应您正在使用的解决方案:

var form = $(this).parent().parent().parent().parent().parent().find('.reply-form');

或只是

var form = $('.reply-form');

jsFiddle示例