简体   繁体   English

单选按钮onclick事件不起作用

[英]radio button onclick event does not work

I'm trying to get onclick event in html radio buttons to call a function in JavaScript program. 我试图在html单选按钮中获取onclick事件来调用JavaScript程序中的函数。

When I use button, it works: 当我使用按钮时,它有效:

HTML5: 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 (in index.js): JavaScript(在index.js中):

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

But when I use radio button, the onclick does not call the function: 但是当我使用单选按钮时,onclick不会调用该函数:

HTML5 (in the same file above): 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 (in index.js): Javascript(在index.js中):

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

What's wrong with my code? 我的代码出了什么问题? Any help? 有帮助吗?

You need to actually call test function. 你需要实际调用test功能。 So this onclick="test" should become 所以这个onclick="test"应该成为

onclick="test()"

It's not enough to just reference function, you need to invoke it with () operator. 仅引用函数是不够的,您需要使用()运算符调用它。

You are missing parentheses. 你缺少括号。 Put onclick="test()" instead 改为onclick="test()"

在行console.log(“test”)的末尾添加分号;

JavaScript function can be invoked without being called. 可以在不调用的情况下调用JavaScript函数。 Please see this 请看这个

I think your javascript is loading before your html ready, you can solve this problem by using your code in body teg or you can use window.onload in your index.js file.Try bellow code I think it will work. 我认为你的javascript是在你的html准备好之前加载的,你可以通过在body teg中使用你的代码来解决这个问题,或者你可以在index.js文件中使用window.onload。尝试下面的代码我认为它会起作用。

function test()
{
    alert("Hi");
}


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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