简体   繁体   中英

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.

//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.

Like so:

btn1.dataset.correctOrNot = true

Then you test that value in your fSubmit function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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