有人可以帮助我吗?我想在 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:我是 stackoverflow 的新手 :)
最佳答案
您的代码中有一些错误。看看这个简化的:
<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>
关于javascript - 无法将 setAttributeNode 应用于文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32517452/