问题描述
我有这样的代码:
<html>
<head>
<script language="javascript">
window.onload = function() {
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(self.id)");
document.body.appendChild(x);
}
}
function isTOF(v) {
alert(v);
}
</script>
</head>
<body>
</body>
</html>
我想让它提醒自己的字母(值),但是它不起作用.
I wanted to make it alert its own alphabet(value), but it doesn't work.
例如,当我单击按钮"时,程序应提醒"A".
So for example, when I click A Button, the program should alert 'A'.
但是它会警告未定义".
But it alerts 'undefined'.
我不知道问题出在哪里.
I don't know what the problem is.
我想让我的代码正常工作.
I want to make my code work properly.
我该怎么做?
推荐答案
您遇到的问题是由于未定义self
引起的.相反,您应该使用已经设置的值,并将this
传递给isTOF
:
The problem you are having is caused by self
not being defined. Instead, you should use the value that you already set, and pass in this
to isTOF
:
<html>
<head>
<script language="javascript">
window.onload = function() {
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)");
document.body.appendChild(x);
}
}
function isTOF(v) {
alert(v.value);
}
</script>
</head>
<body>
</body>
</html>
这样,您要将元素的引用传递给isTOF
,以防您要对其进行任何操作或仅出于信息目的.
This way, you are passing a reference to the element to isTOF
in case you want to do anything with it or just for purely information purposes.
希望这会有所帮助!
这篇关于JavaScript字串未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!