【问题标题】:How to get Jquery to Show/Hide Dynamic Div Element?如何让 Jquery 显示/隐藏动态 Div 元素?
【发布时间】:2012-05-13 06:10:38
【问题描述】:

我想使用 JQuery 复制以下 javascript 代码,这样页面就不必刷新。我在使用 Jquery 时遇到的主要问题是,我想要选择的 div 会根据评论 id 的不同而有所不同,评论 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>

【问题讨论】:

    标签: javascript jquery django


    【解决方案1】:

    你好演示 http://jsfiddle.net/gpwnn/

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

    代码

    toggle_visibility = function (id){
    
       var e = $("#"+id);
       e.toggle();
    }​
    

    【讨论】:

      【解决方案2】:

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

      $( '#' + id ).toggle();
      

      【讨论】:

        【解决方案3】:
        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();
        }
        

        【讨论】:

          【解决方案4】:

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

          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/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-07-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-25
            • 2013-09-17
            • 1970-01-01
            相关资源
            最近更新 更多