javascript - 在 Javascript 中调用带参数的函数和 OnClick 触发不带参数的函数之间的区别?

标签 javascript html

看到这样的代码:

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/

相关文章:

javascript - 为什么加载js一次就不行了,而css却可以呢?

javascript - 从传单弹出窗口内的复选框访问功能

css - 在使用 CSS 单击父 div 后,使 div a 出现并停留

php - 将MYSQL表信息放入html表

HTML 视频标签 Safari

javascript - 响应表不显示列值

javascript - 在 Angular 中访问嵌套的json并在php中显示

javascript - 克隆带有值的 html 表单

javascript - 如何在angularjs Material 设计中显示标签标题居中对齐

html - 如何禁止 firefox 密码字段完成?