看到这样的代码:
index.html
<script type = "text/javascript" src = "choices.js" ></script>
<form id = "myForm" action = "">
<p>
<label> <input type = "radio" name = "myChoice" value = "A" />
A </label>
<br />
<label> <input type = "radio" name = "myChoice" value = "B" />
B </label>
<br />
<label> <input type = "radio" name = "myChoice" value = "C"/>
C </label></form>
<script type = "text/javascript" src = "choicesDom.js" ></script>
choices.js
function userChoice (choice) {
var dom = document.getElementById("myForm");
for (var index = 0; index < dom.myChoices.length; index++) {
if (dom.myChoices[index].checked) {
choice = dom.myChoices[index].value;
break;
}
}
choicesDom.js
var dom = document.getElementById("myForm");
dom.elements[0].onclick = userChoice;
dom.elements[1].onclick = userChoice;
dom.elements[2].onclick = userChoice;`
问题是:为什么在 choicesDom.js
中,userChoice
被像变量一样调用?为什么不需要参数,为什么不是 userChoice()
或 userChoice(value)
?尝试时,它显示为语法错误。
javascript函数的规则是什么?与其他编程语言的函数相比,它的使用似乎相当宽松
最佳答案
这很简单。在 Javascript 中,函数是一等公民,这意味着您可以像更广泛意义上的变量一样使用它们。在代码示例的最后一部分中,定义的函数“userChoice”被分配给给定元素的每个 onclick 函数。
你问的问题是错误的。在最后一部分中,该功能未触发。
如何以类似变量的方式使用函数的简短示例(函数是一等对象)
// define some function
function someFunction(val){
console.log(val);
}
// creates an object which has a reference to this function
var obj = someFunction;
// calls the function via obj
obj("Hi");
无论您发布的代码应该完成什么任务,这是一个修正版本,删除了所有主要语法错误:
function userChoice (choice) {
var dom = document.getElementsByName("myChoice");
for (var index = 0; index < dom.length; index++) {
if (dom[index].checked) {
choice = dom[index].value;
break;
}
}
console.log(choice);
}
var dom = document.getElementsByName("myChoice");
dom[0].onclick = userChoice;
dom[1].onclick = userChoice;
dom[2].onclick = userChoice;
<form id = "myForm" action = "">
<p>
<label> <input type = "radio" name = "myChoice" value = "A" />
A </label>
<br />
<label> <input type = "radio" name = "myChoice" value = "B" />
B </label>
<br />
<label> <input type = "radio" name = "myChoice" value = "C"/>
C </label></form>
关于javascript - 在 Javascript 中调用带参数的函数和 OnClick 触发不带参数的函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52438388/