我试图将 Canvas 元素添加到 DOM 中,然后在设定的时间后将其删除。 Killbox() 函数被调用,但元素并未被删除。我相信我的语法是正确的,并且删除动态添加的 DOM 元素存在一些根本问题。
//con 是 console.log() 的缩写
function spawnCanvas(e) {
con(e);
var boxheight=50;
var boxwidth=50;
var xpos = e.clientX - boxwidth/2;
var ypos = e.clientY - boxheight/2;
var id = xpos.toString() + ypos.toString();
con("id:" + id);
var tag = "<canvas width='" + boxwidth +
"' height='" + boxheight +
"' style='position:absolute; border:1px solid #000; left:" +
xpos + "px; top:" + ypos + "px;' id='" + id + "'></canvas>";
con(tag);
var t = $(tag);
$("body").append(t);
var p = setTimeout("killbox(" + id + ")", 1500);
}
function killbox(id){
con("in killbox. id:" + id);
$('#id').remove();
}
最佳答案
在 killbox
中,您将删除具有文字 id id
的元素。相反尝试;
$('#' + id).remove();
以上将删除具有“id”变量设置的 id 的元素。
关于javascript - 为什么 jQuery remove() 在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3484301/