简体   繁体   中英

.slideDown (jQuery) not working

This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. 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:

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

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

This is the sample data returned by the GET request:

[{"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);
    // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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