简体   繁体   English

如何将函数的变量链接到按钮的变量?

[英]How to link the variable for the function to the button's variable?

Im new to javascript, is there any way to link my function's var to the button so that the function can be executed properly.I cant seem to link the function's variable to the button's id or even the button itself. 我是javascript的新手,有什么方法可以将函数的var链接到按钮,以便函数可以正确执行。我似乎无法将函数的变量链接到按钮的id甚至按钮本身。

//My button
 var btn1 = document.createElement('button');
 btn1.textContent = questions[0].A
 btn1.id = 'optionA'
 document.body.appendChild(btn1);
 btn1.addEventListener('click', fSubmit);   

//My Function
var score=0;
function fSubmit(){
var correctanswer=btn1;
if(correctanswer.checked==true){
score++;
alert("Answer is correct! "+"Your Score is now "+score++)}
else{
alert("Answer is incorrect!")}
}

what I think you are trying to say is that you want to bind the "correctness" of a button's data to the score. 我想您想说的是,您想将按钮数据的“正确性”绑定到得分。 What I would do is add a custom data attribute to each button containing 'true' or 'false' value for that button. 我要做的是向每个包含该按钮“ true”或“ false”值的按钮添加自定义数据属性

Like so: 像这样:

btn1.dataset.correctOrNot = true

Then you test that value in your fSubmit function: 然后,在fSubmit函数中测试该

if (btn1.dataset.correctOrNot === true) {
  // etc. etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM