[英]Changing the value of buttons with JavaScript
Whenever I click on a certain letter, I want the first slot value
from the beginning to be changed to the letter value
I clicked on. 每当我点击某个字母时,我都希望从开头的第一个插槽
value
更改为我点击的字母value
。 Is it correct that I put the letter.onclick = letterClick(this);
我把
letter.onclick = letterClick(this);
放在letter.onclick = letterClick(this);
是否正确letter.onclick = letterClick(this);
into the for
loop or should I realise it some other way. 进入
for
循环或者我应该以其他方式实现它。 Also, what should the letterClick()
function contain? 另外,
letterClick()
函数应该包含什么?
// Makes slots and letters for the chosen word.
function maker() {
for (i=0; i<word.length; i++) {
var slot = document.createElement("input");
var letter = document.createElement("input");
var letters=(shuffledWord).split("");
slot.type = "submit";
slot.value = "";
slot.id = "slot" + i;
slot.setAttribute('id', 'slot');
letter.type = "submit";
letter.value = letters[i];
letter.id = "letter" + i;
letter.onclick = letterClick(this);
letter.setAttribute('id', 'letter');
document.getElementById("slotbar").appendChild(slot);
document.getElementById("letterbar").appendChild(letter);
}
}
Not really, this
refers to the context where you run the method maker
. 不是,
this
指的是运行方法maker
的上下文。 So mostly you get this as window, and you do not want to invoke the function when you bind the handler for onClick. 因此,大多数情况下,您将此视为窗口,并且在绑定onClick的处理程序时不希望调用该函数。 It should be a function reference.
它应该是一个功能参考。
Try 尝试
letter.onclick = letterClick.bind(this, letter);
Now the function will be invoked with your first argument as that letter element. 现在,将使用您的第一个参数作为该字母元素调用该函数。
When you do 当你这样做
letter.onclick = letterClick(this);
it immediately invokes the function and set its result as handler, ie if it doen't return another function ref that is the real handler, it won't work. 它立即调用函数并将其结果设置为处理程序,即如果它不返回另一个函数ref,它是真正的处理程序,它将无法工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.