0

我正在用 javascript 创建一堆 div,并且在某个时间我希望删除所有 div。

我的代码是这样的:

function CreateDiv(width, height, row, col){
var thisTile = document.createElement("div");
thisTile.style.position = "absolute";
thisTile.style.width = width + "px";
thisTile.style.height = height + "px";
thisTile.style.top = row*TileH + topMargin + "px";
thisTile.style.left = col*TileW + leftMargin +"px";
thisTile.style.backgroundImage = "url(" + imagePath + ")";
thisTile.style.backgroundSize = imageWidth + "px " + imageHeight +"px";
thisTile.style.backgroundRepeat = "noRepeat";
thisTile.style.backgroundPosition =  "-" + col*TileW + "px -" + row*TileH + "px";
thisTile.onclick = TileClicked;
thisTile.name = "tiles";
document.body.appendChild(thisTile);
return thisTile;
}
...
var tmp = document.getElementsByName("tiles");
alert("tmp length: " + tmp.length);
for (var i = 0; i < tmp.length; i++)
document.body.removeChild(tmp[i]);

但每次 tmp 都是一个空数组,所以我实际上无法删除我想要的 div,

我试图改变

tile.name = "tiles"

tile.nodeName = "tiles"

或者

tile.className = "tiles"

但是它们都不起作用,我只是想知道元素的哪个名称属性或属性究竟是getElementsByName中的那个?

4

3 回答 3

1

getElementsByName方法返回一个元素列表,其属性名为name,具有给定值,但仅适用于 HTML 规范允许此类属性的元素。并且div不在其中。

实际上,情况要复杂一些。现代浏览器(包括 IE 10)实际上实现了它,以便考虑HTML 标记name中具有该属性的所有元素,即使该标记在 HTML 规范中无效,例如. 但不是只有在 JavaScript 中分配了属性的元素。不同的是,标记属性也会导致信息被添加到对象中。<div name=tiles>foo</div>nameattributes

所以如果你真的,真的想在name这里使用(你不应该),你可以替换

tile.name = "tiles"

经过

thisTile.setAttribute("name", "tiles");

它仍然无法在 IE 9 及更早版本上运行。

从问题中的目的描述来看,如果以后需要删除它们,您似乎应该只收集已添加的元素数组。也就是说,除了在文档中添加一个元素之外,您还可以将它附加到您创建的数组中,然后,当您需要将它们全部删除时,您只需遍历数组即可。

于 2013-09-19T05:17:58.257 回答
0

实际上DIV标签没有名称属性。

检查以下参考:

http://www.w3schools.com/tags/tag_div.asp

为您的 div 提供特定的class访问权限,然后使用:

elements = document.getElementsByClassName(className)
于 2013-09-19T04:36:45.037 回答
0

在您的代码中,您使用了以下代码,包括tiles-

thisTile.name = "tiles";

var tmp = document.getElementsByName("tiles");

但是您必须使用tiles[]代替tiles来制作tiles元素数组。这是您的代码中唯一的错误。如果您更改这两个语句,您的代码将运行良好。

于 2013-09-19T06:09:10.617 回答