我正在尝试删除动态创建的 DOM 元素,但出于某种原因我无法让它工作。
它可以很好地创建对象并使用我指定的 ID,但它不会删除。
if
语句的检查工作正常,因为它打印出 console.log()
。
有什么想法吗?
function displayLive()
{
var previous = null;
var current = null;
setInterval(function()
{
$.ajax({
url: '/showLive',
dataType: 'json',
contentType: 'application/json',
success: function(response)
{
current = JSON.stringify(response);
if(previous !== current)
{
var obj = JSON.parse(response);
console.log(obj);
for(var i = 0; i < obj.active.length; i++)
{
if(obj.active[i].active === true)
{
$('.left').prepend($('<div/>', {class: 'profTemp', id: obj.active[i].userNameData}).append(
$('<img/>', {src: obj.active[i].profiler, width: 40, height: 40}),
$('<span/>', {text: " " + obj.active[i].userNameData})));
}
else if(obj.active[i].active === false)
{
$('#%s' , obj.active[i].userNameData).remove();
console.log("getting in false");
}
}
}
}
});
previous = current;
}, 2000);
}
最佳答案
用户名中有一个点(或其他选择字符)。使用
$(document.getElementById(obj.active[i].userNameData)).remove()
为了解决这个问题。
关于javascript - 使用 jQuery 按 ID 删除 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763573/