getElementsByClassName产生错误“未定义” [英] getElementsByClassName produces error "undefined"

查看:410
本文介绍了getElementsByClassName产生错误“未定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个文本框,类输出。我希望能够在 div 中将其值打印为纯HTML列表,其中 ID 组合。现在,我有以下代码:

I have several textboxes with the class output. I would like to be able to print their values as a plain HTML list in a div with ID combined. Right now, I have the following code:

function doCombine() {
    document.getElementById('combined').innerHTML =
    document.getElementsByClassName('output').value + ",";  
}

然而,当我运行该函数时,我收到错误消息未定义 ,.当我在 .value 之前添加 [0] 时,它可以工作,但只有第一个<$ c的值$ c> textbox 正在显示。我在某处读到 [i] 会显示所有值,但这似乎不起作用。

Yet, when I run the function, i get the error message undefined,. When i add a [0] before .value, it works, but only the value of the first textbox is showing up. I read somewhere that [i] will show all the values, but that doesn't seem to work.

我做错了什么?

推荐答案

getElementsByClassName



返回具有所有给定类名的元素集。在文档对象上调用时,将搜索完整文档,包括根节点。您也可以在任何元素上调用getElementsByClassName;它将仅返回具有给定类名的指定根元素的后代元素。

getElementsByClassName

Returns a set of elements which have all the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName on any element; it will return only elements which are descendants of the specified root element with the given class names.

所以你应该这样做

var elements = document.getElementsByClassName('output');
var combined = document.getElementById('combined');
for(var i=0; i < elements.length; i++) { 
  combined.innerHTML += elements[i].value + ",";
}

这篇关于getElementsByClassName产生错误“未定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆