getElementByID有效,getElementsByClassName没有 [英] getElementByID works, getElementsByClassName does not
问题描述
我正在研究一种动态添加选择输入/下拉框到页面的解决方案。下面的示例代码如果我给每个选择输入一个唯一的id并使用getElementById()包含一行cod4e到脚本,但是如果我使用GetElementsByClassName()则不起作用。
I'm working on a solution that dynamically adds select input / dropdown boxes to a page. The example code below works if I give each select input a unique id and include a line of cod4e to the script using getElementById() but does not work if I use GetElementsByClassName().
我的目标是使用一个脚本填充选择输入框,而无需为脚本选择输入和相应代码分配唯一ID。
My objective is to use one script to populate select input box without the need to assign a unique id to select inputs and corresponding code to the script.
<select class="p1"></select>
<select class="p1"></select>
<select class="p1"></select>
<script>
var Date1 = "<option>" + new Date(new Date().getTime()+(1*24*60*60*1000)).toDateString() + "</option>";
var Date2 = "<option>" + new Date(new Date().getTime()+(2*24*60*60*1000)).toDateString() + "</option>";
var Date3 = "<option>" + new Date(new Date().getTime()+(3*24*60*60*1000)).toDateString() + "</option>";
var Date4 = "<option>" + new Date(new Date().getTime()+(4*24*60*60*1000)).toDateString() + "</option>";
var Date5 = "<option>" + new Date(new Date().getTime()+(5*24*60*60*1000)).toDateString() + "</option>";
var Date = Date1 + Date2 + Date3 + Date4 + Date5
document.getElementsByClassName("p1").innerHTML = Date;
</script>
推荐答案
getElementsByClassName()
function(注意Elements中的 s )返回NodeList,而不是单个节点。您必须遍历列表才能单独对每个节点进行操作。
The getElementsByClassName()
function (note the s in "Elements") returns a NodeList, not a single node. You have to iterate through the list to operate on each node individually.
您可以使用简单的进行
循环:
You can do it with a simple for
loop:
var selects = document.getElementsByClassName("p1");
for (var i = 0; i < selects.length; ++i)
selects[i].innerHTML = Date;
我强烈怀疑你的代码有另一个问题:你正在创建一个名为Date的全局变量,这将破坏JavaScript日期构造函数绑定。使用其他名称(如小写日期)。
I suspect strongly that your code has another problem: you're creating a global variable called "Date", and that will clobber the JavaScript "Date" constructor binding. Use another name (like lower-case "date").
这篇关于getElementByID有效,getElementsByClassName没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!