无法将 setAttributeNode 应用于文本区域

Can't apply the setAttributeNode to a textarea

有人可以帮助我吗?我想在 textarea 上做这样的事情来设置 maxlength 属性:

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
    color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>

<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var h1 = document.getElementsByTagName("H1")[0];
    var att = document.createAttribute("class");
    att.value = "democlass";
    h1.setAttributeNode(att);
}
</script>

</body>
</html>

我的代码是:

<!DOCTYPE html>
<html>
<head>
<style>
</head>
<body>

<textarea>Hello World</textarea>

<button onclick="myFunction()">change max length</button>

<script>
function myFunction() {
    var text = document.getElementsByTagName("textarea");
    var att = document.createAttribute("maxlength");
    att.value = "100";
    text.setAttributeNode(att);
}
</script>

</body>
</html>

如果我通过单击按钮 运行 脚本,控制台会显示:

Uncaught TypeError: h1.setAttribute is not a function.

Ps:我是 Whosebug 的新手:)

你有两个问题:

您必须处理元素而不是集合

比较(特别是每行的最后几个字符):

var h1 = document.getElementsByTagName("H1")[0];
var text = document.getElementsByTagName("textarea");

在第一种情况下,您正在尝试处理文档中的第一个 H1。在第二个中,您正在尝试处理所有文本区域的集合。

集合不是元素,也没有元素所具有的所有方法。

您必须处理一个存在的元素

第二组代码中没有textarea。

首先,您忘记了文本区域:

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>
<body>

<h1>Hello World</h1>

<button onclick="myFunction()">change max length</button>
<textarea></textarea>

<script>
    function myFunction() {
        var text = document.getElementsByTagName("textarea");
        var att = document.createAttribute("maxlength");
        att.value = "100";
        text[0].setAttributeNode(att);
    }
</script>

</body>
</html>

还有 document.getElementsByTagName returns 你一个数组所以你得到 'h1.setAttribute is not a function.' 错误。

您的代码中有一些错误。看看这个简化版:

jsFiddle

<h1>Hello World</h1>

<textarea rows="10" cols="40"></textarea><br />
<button onclick="myFunction()">change max length</button>

<script>
    function myFunction() {
    var text = document.getElementsByTagName("textarea")[0];
    text.setAttribute("maxlength", 100);
}
</script>