4

我想使用 JQuery 复制以下 javascript 代码,这样页面就不必刷新。我在使用 Jquery 时遇到的主要问题是,我想要选择的 div 会根据评论 id 而有所不同,其中可能有数百个。非常感谢任何帮助或建议!

<head>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'visible';
   else
      e.style.display = 'block';
}
//-->
</script>
</head>
<body>
{% for comment in comments %}
<a href="#" onclick="toggle_visibility('make_reply_{{comment.id}}');">Reply</a>
<div id="make_reply_{{comment.id}}">
<form name="titleform" action="/{{slug}}/reply/" method = "post">
    <input type="hidden" name="id" value="{{comment.id}}"</input>
{% csrf_token %}
<textarea name = "comment" value="" rows="7" cols="50"></textarea><br>
<input type="submit" value="Submit"/>
</form>
</div>
{% endfor %}
</body>
4

4 回答 4

3

HIya演示 http://jsfiddle.net/gpwnn/

API 链接:http ://api.jquery.com/toggle/

代码

toggle_visibility = function (id){

   var e = $("#"+id);
   e.toggle();
}​
于 2012-05-13T06:16:31.677 回答
2

由于您使用的是 jQuery,请$.toggle()改用:

$( '#' + id ).toggle();
于 2012-05-13T06:16:07.823 回答
1
function toggle_visibility(id) {
   var $e = $('#' + id);
   if($e.is(':visible'))
      $e.hide();
   else
     $e.show();
}

要不就$e.toggle();

function toggle_visibility(id) {
   var $e = $('#' + id);
   $e.toggle();
}
于 2012-05-13T06:16:56.343 回答
0

如果我必须这样做,我会以更简单的方式进行,如下所示:

HTML:

 {% for comment in comments %}
 <div id="{{comment.id}}"> // this div will separate each iterate elements
   <a href="#">Reply</a> // no inline method required in jquery
   <form name="titleform" action="/{{slug}}/reply/" method = "post">
     <input type="hidden" name="id" value="{{comment.id}}"/>
     <textarea name = "comment" value="" rows="7" cols="50"></textarea><br>
     <input type="submit" value="Submit"/>
   </form>
 </div>
 {% endfor %}

jQuery

 $('a').click(function(){
   $(this).next('form').toggle();
 });

小提琴:http: //jsfiddle.net/VjthL/2/

于 2012-05-13T06:38:03.657 回答