jQuery / json循环没有给我完整的结果.html()

时间:2012-08-30 10:34:38

标签: arrays json jquery

// Calling the video function with JSON

$.getJSON("videos.php", function(data){
// first check if there is a member available to display,
//if not then show error message
    if(data == '') { 
        $('#tabs-4').html("<div class='errorMember'>Sorry, there is currently no member available videos</div>");
    } 
    // if there is a member, then loop through each data available
    else {
          $.each(data, function(i,name){
            content = '<div class="left"><img src="' + name.pic + '"/>';
            content += '<p>' + name.name + '</p>';
            content += '<a href="' + name.link + '" target="_blank">Video link</a>';
            content += '</div><br/><hr>';
            $("#tabs-4").html(content);
        });
    }
});​

问题是它只给了我一个结果而不是数组的结果列表,但是如果我appendTo(内容)..它在当前不是我想要的结果中添加完整的结果列表,因为我需要使用更新的数据刷新该内容。

对我做错的任何想法?

3 个答案:

答案 0 :(得分:1)

可能到目前为止只有最后一个元素显示。

// Calling the video function with JSON

$.getJSON("videos.php", function(data){

    // first check if there is a member available to display, if not then show error message
    if(data == '') { 
        $('#tabs-4').html("<div class='errorMember'>Sorry, there is currently no member available videos</div>");
    } 
    // if there is a member, then loop through each data available
    else {
        //If you want to Clear the Container html
        $("#tabs-4").html(''); 
        $.each(data, function(i,name){
            content = '<div class="left"><img src="' + name.pic + '"/>';
            content += '<p>' + name.name + '</p>';
            content += '<a href="' + name.link + '" target="_blank">Video link</a>';
            content += '</div><br/><hr>';
            $("#tabs-4").append(content);
        });
    }
});

答案 1 :(得分:0)

如果我很好理解,可能你可能想要做这样的事情

...
else {
        $("#tabs-4").empty(); // remove previous data (if any)

        $.each(data, function(i,name){
            content = '<div class="left"><img src="' + name.pic + '"/>';
            content += '<p>' + name.name + '</p>';
            content += '<a href="' + name.link + '" target="_blank">Video link</a>';
            content += '</div><br/><hr>';

            $("#tabs-4").append(content); // append new data
        });
}

答案 2 :(得分:0)

在填充之前清空元素:

$('#tabs-4').empty();
$.each(data, function(i,name){
  var content =
    '<div class="left"><img src="' + name.pic + '"/>' +
    '<p>' + name.name + '</p>' +
    '<a href="' + name.link + '" target="_blank">Video link</a>' +
    '</div><br/><hr>';
  $("#tabs-4").append(content);
});

或者在将它放入元素之前将所有元素放在字符串中:

var content = '';
$.each(data, function(i,name){
  content +=
    '<div class="left"><img src="' + name.pic + '"/>' +
    '<p>' + name.name + '</p>' +
    '<a href="' + name.link + '" target="_blank">Video link</a>' +
    '</div><br/><hr>';
});
$("#tabs-4").html(content);