我不明白为什么这不起作用:(
<textarea class="js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0" placeholder="What's happening?" style="height: 130px;"></textarea>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0").value = "TESTESTTEST";
}
</script>
&#13;
答案 0 :(得分:2)
getElementsByClassName
返回一个类似数组的对象,因此您需要指定document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0")[0].value = "TESTESTTEST";
<textarea class="js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0" placeholder="What's happening?" style="height: 130px;"></textarea>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0")[0].value = "TESTESTTEST";
}
</script>
&#13;
答案 1 :(得分:1)
在javascript中,多个textarea或div可以具有相同的类名,但具有唯一的ID&#39; s。当你通过它的id访问任何元素时,它是唯一的,你可以通过它的Id调用它,但是当你按名称访问元素时,你必须按索引访问相同类名下的每个元素,如下所述 -
<textarea class="text" id="1"></textarea> //First textarea
<textarea class="text" id="2"></textarea> //Second textarea
<textarea class="text" id="3"></textarea> //Third textarea
<textarea class="text" id="4"></textarea> //Fourth textarea
访问第3个文本区域 -
document.getElementById("3");
//OR
document.getElementsByClassName("text")[2];
两个代码都会做同样的事情