这是Javascript的新手,这一点让我有点困扰。我基本上是想做一个打地鼠型的游戏。一旦我添加了图像,我想逐个删除它们。我想我已经添加了唯一的I,但是当我添加图像删除时,一切都停止了。我做错了什么?除了.remove之外,我还想寻找其他项目,但我不确定这部分代码叫什么(方法、函数等)。我的代码如下。
function addMole(){
var xPos = randomPosX();
var yPos = randomPosY();
var count=0;
$("#gamespace").append('<img src="img/roach.png" style="left: '+xPos+'px; top: '+yPos+'px;" id="img'+count+'"/>');
var r=Math.floor(Math.random()*2000);
t=setTimeout("addMole();", r);
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");
count++;
}发布于 2015-05-03 10:35:26
你有一些无效的引用:
function addMole(){
var xPos = randomPosX();
var yPos = randomPosY();
var count=0;
$("#gamespace").append('<img src="img/roach.png" style="left: '+xPos+'px; top:' + yPos + 'px;" id="img'+count+'"/>');
var r=Math.floor(Math.random()*2000);
t = setTimeout(addMole, r);//is t defined already?
$("#gamespace").remove("#img" + count).removeAttribute("img" + count);//why you need removeAttribute
count++;
}发布于 2015-05-03 10:36:01
所有内容都停止工作,因为这一行不是有效的JavaScript:
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");检查您的报价:虽然'...'和"..."可以互换,但单个"和'不能互换。
另一个问题是,在修复上述问题之后,您的代码逻辑无法正常工作:您添加了一个图像,然后立即将其删除。我不太清楚您正在尝试做什么,所以我不能为您重写它;我能做的最多就是告诉您更详细地定义您的流程。
最后,当您以编程方式创建元素时,保留元素引用通常更好,也不容易失败,而不是弄乱ID。
var $gamespace = $('#gamespace');
var $img = $('<img>').css({
left: left,
top: top
}).appendTo($gamespace);
// ...
$img.remove();发布于 2015-05-03 10:39:52
使用
$("#gamespace").find("#img'"+count+"'").remove();而不是
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");或者..。虽然镜像ID是唯一的,但您可以直接使用
$("#img'"+count+"'").remove();https://stackoverflow.com/questions/30009635
复制相似问题