javascript innerHTML 不适用于 JS 中的类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10845109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
innerHTML not working with classname in JS
提问by swapnesh
My drop down List to select particular value-
我的下拉列表选择特定值-
<select name="category" id="category" onChange="showDiv(this.value);" >
<option value="">Select This</option>
<option value="1">Nokia</option>
<option value="2">Samsung</option>
<option value="3">BlackBerry</option>
</select>
This is the div where i want to show the text
这是我想显示文本的 div
<span class="catlink"> </span>
<span class="catlink"> </span>
And this is my JS function -
这是我的 JS 函数 -
function showDiv( discselect )
{
if( discselect === 1)
{
alert(discselect); // This is alerting fine
document.getElementsByClassName("catlink").innerHTML = "aaaaaaqwerty"; // Not working
}
}
Let me know why this is not working, and what i am doing wrong?
让我知道为什么这不起作用,我做错了什么?
回答by
document.getElementsByClassName("catlink")
is selecting all the elementsin webpage as arraytherefore you have to use [0]
document.getElementsByClassName("catlink")
正在选择网页中的所有元素作为数组,因此您必须使用[0]
function showDiv( discselect )
{
if( discselect === 1)
{
alert(discselect); // This is alerting fine
document.getElementsByClassName("catlink")[0].innerHTML = "aaaaaaqwerty"; // Now working
}
}
回答by KooiInc
You ar creating a nodeList
(a special array of Nodes) using getElementsByClassName
. Alternatively you can use document.querySelector
, which returns the first element with className .catlink
:
您正在nodeList
使用getElementsByClassName
. 或者,您可以使用document.querySelector
,它返回带有 className 的第一个元素.catlink
:
function showDiv( discselect ) {
if( discselect === 1) {
document.querySelector(".catlink").innerHTML = "aaaaaaqwerty";
}
}