开发者

Jquery looping results

I'm trying to loop all matched results so they appear in a list form. I have tried using $('div#comments').html(commentdata); - but it only shows me the first match of data / the first comment.

I then tried using .append instead of .html, this shows all the comments ok - but adds all the data on again everytime I run the onClick event that is attached to the request.

In short; how can I list all of my comments, without them being added/appended every time I click on the object that l开发者_如何学编程oads them.


var xml = data.responseXML;

var comments = xml.documentElement.getElementsByTagName("comment");

for (var i = 0; i < comments.length; i++) {

      var user = comments[i].getAttribute("username");
      var comm = comments[i].getAttribute("comment");
      var commentdata = "<li>"+ user +" - " + comm +"</li>";

      $('div#comments').append(commentdata);

}


var xml = data.responseXML;

var comments = xml.documentElement.getElementsByTagName("comment");

// html collection
var commentdata = [];

// open <ul>
commentdata.push('<ul>');

// cache this
var len = comments.length;
for (var i = 0; i < len; i++) {

      var user = comments[i].getAttribute("username");
      var comm = comments[i].getAttribute("comment");

      // add <li> element
      commentdata.push("<li>"+ user +" - " + comm +"</li>");

}

// end <ul>
commentdata.push('</ul>');

// update <div id="comments"> contents
$('div#comments').html(commentdata.join("\n"));

Praveen is also correct, you could just empty the container before you start appending data:

$('div#comments').empty();


    var xml = data.responseXML;

    var comments = xml.documentElement.getElementsByTagName("comment");

// clear previous data here
    $('div#comments').empty();

    for (var i = 0; i < comments.length; i++) {

          var user = comments[i].getAttribute("username");
          var comm = comments[i].getAttribute("comment");
          var commentdata = "<li>"+ user +" - " + comm +"</li>";

          $('div#comments').append(commentdata);

    }


You may be looking for the .one() event-attachment method. So e.g.

$("#id-of-thing-to-click").one("click", function () {
    // the code from your post
});

The click event will then only be triggered the first time someone clicks on #id-of-thing-to-click, instead of every time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜