简体   繁体   English

.slideDown(jQuery)无法正常工作

[英].slideDown (jQuery) not working

This is my jQuery code to add html generated by a post in a div. 这是我的jQuery代码,用于添加由div中的帖子生成的html。 The slidedown() function doesn't seem to be working right. slidedown()函数似乎无法正常工作。 Here is my script: 这是我的脚本:

$(".expand").click(function(){
      var button = $(this);
      var id = $(this).attr("eid");
      var url = "/get-complete/" + id + '/';
      $.ajax({  
        type: "GET", 
        url: url,  
        success: function( data ) { 
          var obj = $.parseJSON(data);
          var lang = '';
          $.each(obj, function() {
            lang += this['html'] + "<br/>";
          });
          button.siblings('.comment-expand').slideDown('slow', function(){
            button.siblings('.comment-expand').html(lang);
          }); 
          button.attr('class', 'collapse');
          button.html('Collapse');
        }, 
      });
      return false;
    });

Here is the html: 这是html:

<a class="expand" href="/#" eid="{{ event.id }}">Expand</a>

<div class="comment-expand"></div>

This is the sample data returned by the GET request: 这是GET请求返回的样本数据:

[{"html": "\n    <div class=\"comment-count-bar\">\n</div>\n    "}]

This is the code to collapse the post, but this isn't working either: 这是折叠帖子的代码,但这也不起作用:

$("body").delegate(".collapse", "click", function(){
          var button = $(this);
          button.siblings('.comment-expand').slideUp('slow');
          button.attr('class', 'expand');
          button.html('Expand');
          return false;
        });

Try this: 尝试这个:

$.ajax({  
    type: "GET", 
    url: url,
    // setting the dataType to json, jQuery itself parses the response 
    dataType: 'json', 
    success: function(data) {  
      // Hiding the element and setting it's innerHTML 
      // before calling slideDown()
      button.siblings('.comment-expand').hide().html(function() {
         // Mapping the response and concatenating `html` properties
         // If the response has only one array use:
         // return data[0].html + '<br>'; instead
         return $.map(data, function(v) {
             return v.html + '<br>';
         }).join('');
      }).slideDown(); 
      button.addClass('collapse')
            .removeClass('expand')
            .html('Collapse');
    }, 
});

Edit: Since you are adding the class dynamically you should delegate the event: 编辑:由于您正在动态添加类,您应该委派事件:

$(document).on('click', '.collapse', function() {
    // var button = $(this);
    // ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM