我有这样的代码:
<html>
<head>
<script language="javascript">
window.onload = function() {
var wordlist = [ "A", "BB", "CCC", "DDDD" ];
for(i = 0; i < 26; i++) {
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", String.fromCharCode(i + 65));
x.setAttribute("id", String.fromCharCode(i + 65));
x.setAttribute("onclick", "isTOF(this.id, wordlist[3])");
document.body.appendChild(x);
}
}
function isTOF(v, word) {
console.log(word);
}
</script>
</head>
<body>
</body>
</html>
我认为console.log(word)
会给我看“ DDDD”,但它是这样说的:
未定义单词列表
我如何使其运行?
答案 0 :(得分:1)
参数字符串未正确连接,应为:
x.setAttribute("onclick", "isTOF(this.id, '" + wordlist[3] + "')")
尽管我更喜欢使用Template Literals来允许嵌入表达式:
<html>
<head>
<script language="javascript">
window.onload = function() {
var wordlist = [ "A", "BB", "CCC", "DDDD" ];
for(i = 0; i < 26; i++) {
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", String.fromCharCode(i + 65));
x.setAttribute("id", String.fromCharCode(i + 65));
x.setAttribute("onclick", `isTOF(this.id, '${wordlist[3]}')`);
document.body.appendChild(x);
}
}
function isTOF(v, word) {
console.log(word);
}
</script>
</head>
<body>
</body>
</html>