I have a blank div called "content". Links are later added to "content" using jquery append. Using empty() does not work; I am guessing empty() wont clear the links added by jquery because the links are not added to the DOM?
function should clear, then display new links, but its not clearing the links, just appending to whatever was present.
function getSubRedditLinks(url)
{
$("#content").empty(); //doesnt work
$.getJSON(
url + suffix,
function foo(data)
{
$("#content").empty(); //doesnt work
$.each(
data.data.children,
function (i, post)
{
$("#content").append( '<section>' +
'<a href="#">' + post.data.title + '</a>' +
'</section>' );
}
);
}
);
$("#content").empty(); //doesnt work
}
Function is called like this:
<li><a开发者_如何学运维 class="link" href="#" onclick=getLinks("localhost")>Blogroll</a></li>
Apparently, empty() should work. I simplified my code above, put its not working in the 3 places I put them. It just keeps adding links to the #content
Try this out:
function getLinks(url)
{
$.getJSON(
url + suffix,
function(data)
{
var items = [];
$.each(
data.data.children,
function (i, post)
{
var section = $('<section></section>').append('<a></a>');
section.find('a').attr('href', '#post=post-' + i).text(post.data.title);
items.push(section[0].outerHTML);
}
);
$('#content').empty().append(items.join(''));
});
}
Use $(...).remove()
instead... Or $("#content").html("")
Works for me, check this out
http://jsfiddle.net/gzNFK/2/
note: remove the comment to use it
精彩评论