innerHTML无法与getElementsByClassName一起使用 [英] innerHTML isn't working with getElementsByClassName

查看:263
本文介绍了innerHTML无法与getElementsByClassName一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个初学者.我正在尝试使用innerHTML. 我想我写了正确的代码,但是没有用. 当我单击触发器时,页面变为白色并显示状态:正在连接" 我不知道问题出在哪里

I'm just a beginner. And I'm trying to use innerHTML. I think I wrote proper code, but it doesn't work. When I click the trigger, the page becomes white and showing the statut : 'connecting' I don't know where is the problem

请有人帮助我.

这是我的密码.

HTML代码

<div class = "head">
<nav>
<a onClick="open()">

<div class = "body">
<div class = "bodyL">
<div class = "newsPnT">

JAVASCRIPT CODE

JAVASCRIPT CODE

function open() {
   document.getElementsByClassName('newsPnT').innerHTML = "asdfasdfasdf";
}

我的代码有什么问题?

PS:我正在使用Firefox Aurora.当我单击触发器时,调试器>源"会显示正在等待源".

PS: I'm using Firefox Aurora. When I click the trigger, the 'debugger > sources' says, 'waiting for sources.'

推荐答案

getElementsByClassName()返回带有元素的数组.

getElementsByClassName() returns array with elements.

返回具有所有给定类名的所有子元素的类似数组的对象.在文档对象上调用时,将搜索完整的文档,包括根节点.您还可以在任何元素上调用getElementsByClassName();它将仅返回具有给定类名称的指定根元素的后代的元素.

Returns an array-like object of all child elements which have all of 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.

因此,您需要迭代数组并像这样设置innerHTML

So you need iterate array and set innerHTML like this i.e.

var elements = document.getElementsByClassName('myClass');
Array.prototype.forEach.call(elements, function(element) {
    element.innerHTML = 'Your text goes here';
});

还有一点好处 JSFiddle

这篇关于innerHTML无法与getElementsByClassName一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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