欢迎
当用户点击我的代码中的每个按钮时,我需要显示一个警告框
示例:用户单击H按钮..警报必须显示H字母
这是代码
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
for(var i = 0; i < key.length; i++)
function printchar()
alert("here how i can print the letter i was clicked ?")
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
document.write("<input type='button' onclick='printchar()' value='" + key[i][j] + "'/>");
document.write("</div>");
答案 0 :(得分:2)
一个简短的方法是使用forEach
遍历数组并创建按钮,将onclick
添加到每个新创建的按钮。
var keys=['A','B','Z'];
keys.forEach(function(key){
var btn=document.createElement('button');
btn.onclick=function(){alert(this.innerHTML);};
btn.innerHTML=key;
document.body.appendChild(btn);
});
答案 1 :(得分:1)
如果你不想完全重新设计你的解决方案(顺便说一句,它缺少一堆花括号),你可以将这封信作为参数传递给你的printchar
函数。 ..
for(var j = 0; j < key[i].length; j++){
document.write("<input type='button' onclick='printchar(\"" + key[i][j] + "\")' value='" + key[i][j] + "'/>");
}
function printchar(letter){
alert(letter);
}
或者,您可以使用事件和closures来避免将JavaScript插入HTML字符串中:
key[i].forEach(function(currentKey){
var btn = document.createElement('input');
btn.value = currentKey;
btn.onclick = function(){
alert(currentKey);
}
// ... now insert btn somewhere on the page
});
答案 2 :(得分:1)
以下是使用您的代码的工作解决方案,以及一些更改:
var key = [["q","w","e","r","t","y","u","i","o","p"],["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
function printchar(letter) {
alert(letter);
}
for(var i = 0; i < key.length; i++) {
document.write("<div>");
for(var j = 0; j < key[i].length; j++) {
document.write("<input type='button' onclick='printchar(this.value);' value='" + key[i][j] + "'/>");
document.write("</div>");
}
}
更改包括:
{
函数和}
循环printchar
和for
)
printchar
函数(作为letter
)