Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中将函数赋值给元素_Javascript - Fatal编程技术网

在javascript中将函数赋值给元素

在javascript中将函数赋值给元素,javascript,Javascript,我是javascript新手,我想将函数fSubmit分配给我的按钮。我做得对吗 我的代码如下: //Button var btn1= document.createElement("BUTTON"); var t1 = document.createTextNode(questions[0].A); btn1.appendChild(t1); document.body.appendChild(btn1); btn1.id='optionA'; btn1.onclick='f

我是javascript新手,我想将函数
fSubmit
分配给我的按钮。我做得对吗

我的代码如下:

//Button
var btn1= document.createElement("BUTTON");      
var t1 = document.createTextNode(questions[0].A);   
btn1.appendChild(t1);
document.body.appendChild(btn1);
btn1.id='optionA';
btn1.onclick='fSubmit()';  
//End of Button

//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 wrong"+"Your Score is now"+score)}
}

对于初学者,您的按钮可以简化

var btn1 = document.createElement('button');
btn1.textContent = questions[0].A
btn1.id = 'optionA'

document.body.appendChild(btn1);
关于添加事件侦听器:

btn.addEventListener('click', fSubmit);

请注意,我传递的函数名不是字符串,也不是使用()调用的<当按下按钮时,code>addEventListener将调用该函数。

Change
btn1.onclick='fSubmit()'
to
btn1.onclick=fSubmit顺便说一句,您的函数没有关闭,您缺少了一个
}
(这就是为什么您应该始终正确缩进,这会使这类事情变得明显)。请仔细阅读:@Eraden该链接有一些非常糟糕的示例:?@Eraden不,他不应该阅读该链接。这两个原因都是因为
onclick=
是非常糟糕的做法,而
w3
是非常糟糕的做法。我同意,但他是新来的。事件驱动编程会让他困惑,最好让他知道简单的方法。随着时间的推移,他了解了什么是最佳实践,以及为什么他不应该使用
onclick
onsubmit
,等等。请不要期望新人成为世界上最好的程序员。他甚至不知道如何附加功能!非常感谢。这是可行的,但有没有什么方法可以让我在这里做一个测验应用时,用一个按钮继续下一个问题