【问题标题】:radio button onclick event does not work单选按钮 onclick 事件不起作用
【发布时间】:2015-03-01 16:05:39
【问题描述】:

我正在尝试在 html 单选按钮中获取 onclick 事件以调用 JavaScript 程序中的函数。

当我使用按钮时,它可以工作:

HTML5:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <script src="index.js"></script>
    ...
  </head>
  <body>
   <button type="button" class="btn btn-default" onclick="clickedButton1()">Button1</button>
...
  </body>
</html>

JavaScript(在 index.js 中):

function clickedButton1 () {
    console.log("clickedButton1")
}

但是当我使用单选按钮时,onclick 不会调用该函数:

HTML5(在上面的同一文件中):

<section id="radioButtons">
    <form action="" method="post" name="radioButtons" id="radioButtons">
        <div class="btn-group" data-toggle="buttons">
            <label class="btn btn-primary active">
                <input type="radio" name="radios" id="radio1" onclick="test()"> Yes
            </label>
            <label class="btn btn-primary">
                <input type="radio" name="radios" id="radio2" onclick="test()"> No
            </label>
        </div>
    </form>
</section>

Javascript(在 index.js 中):

function test () {
    console.log ("test")
}

我的代码有什么问题? 有什么帮助吗?

【问题讨论】:

  • onclick="test" 到 onclick="test()"
  • 我忘了写括号onclick="test()" 。但即使我添加它们,它也不起作用......
  • 我在上面编辑了我的错误。
  • 你是如何检查 console.log() 的?使用警报(“测试”)
  • 在 Chrome 中使用“JavaScript 控制台”。 (这是对您问题的适当回答吗?)

标签: javascript html radio-button


【解决方案1】:

您需要实际调用test 函数。所以这个onclick="test"应该变成

onclick="test()"

仅仅引用函数是不够的,你需要用()操作符来调用它。

【讨论】:

    【解决方案2】:

    您缺少括号。换成onclick="test()"

    【讨论】:

      【解决方案3】:

      在行尾添加分号 console.log("test");

      【讨论】:

        【解决方案4】:

        JavaScript 函数可以在不被调用的情况下被调用。请看this

        【讨论】:

          【解决方案5】:

          我认为你的 javascript 是在你的 html 准备好之前加载的,你可以通过在 body teg 中使用你的代码来解决这个问题,或者你可以在 index.js 文件中使用 window.onload。试试下面的代码,我认为它会起作用。

          function test()
          {
              alert("Hi");
          }
          
          
          window.onload = function()
          {
              document.getElementById("radio1").onclick = test;
          };
          

          【讨论】:

            猜你喜欢
            • 2017-07-18
            • 2014-10-30
            • 2015-11-15
            • 2016-09-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多