0

我在从元素 ID 数组中引用复选框元素时遇到问题。为什么我可以使用文字和字符串 var 作为 getElementById 的参数来引用它,而不是使用数组的元素来引用它?

<html>
<body>

<ul id="zip_wrapper">
<li><label><input type="checkbox" id="72002" value="72002" name="zip_codes[]" checked="checked">72002</label></li>
<li><label><input type="checkbox" id="72034" value="72034" name="zip_codes[]" checked="checked">72034</label></li>
</ul>
<script>

var zips = "";
var tester = "72034";
zips = document.getElementById("zip_wrapper").innerText.split(" ");

//zips =  Array.prototype.slice.call(zips); //a la http://stackoverflow.com/questions/4287681/extremely-annoying-javascript-array-object-error

document.write("zips array, tokenized by split(\" \"): " + zips + "<br />");

document.write("document.getElementById(\"72034\").checked: " + document.getElementById("72034").checked + "<br />");
document.write("document.getElementById(tester).checked: " + document.getElementById(tester).checked + "<br />");
document.write("document.getElementById(zips[1]).checked: " + document.getElementById(zips[1]).checked + "<br />");

</script>
</body>
</html>

您可以在此处查看正在运行的页面:https ://dl.dropbox.com/u/1634015/website/checked.html

4

2 回答 2

1

当我去你的测试页面,当我做

zips = document.getElementById("zip_wrapper").innerText.split(" ");

在控制台中,我将 zips 作为长度为 1 的元素获取,因此zips[1]未定义。似乎(至少在 Chrome 中)innerText 在自己的行上返回了每一个。我除以 \n 并得到:

["72002", "72034", ""]

我认为最重要的问题不在于您使用的是数组中的元素,而是您的数组并没有像您期望的那样组成。

正如 Pointy 指出的那样,Firefox 似乎只是返回 undefined ,而我发现 Chrome 会在各自的行上返回它们(即用“\n”分隔,末尾有一个空字符串)。

您可能需要一种不同的方法来完成您要完成的工作,但原始问题的答案是,使用数组元素作为 getElementById 的参数没有任何问题。

于 2012-06-11T21:53:27.667 回答
0

参数必须是字符串文字,例如

wanted=document.getElementById("myhtmlobject").value

因此,如果您有一系列相似的对象,而不仅仅是一个,

myhtmlobject[1]
myhtmlobject[2]
myhtmlobject[3]
myhtmlobject[4]
etc

然后像这样引用它们

myobj="myhtmlobject[" + j + "]"
wanted= document.getElementById(myobj).value
于 2012-08-29T21:44:50.680 回答