对于单选输入,键入onclick event not working in form tag



我陷入了我认为愚蠢的事情。但现在我已经尝试了每一种组合,但没能发现发生了什么

当我把输入类型放在表单中时,onclick在输入类型单选框中不起作用。但当我删除表单标记时,它起作用。我还看到一个代码,其中onclick在表单标记中工作,但在我写作时不工作。

这不起作用:

<html>
<head>
    <script>
    function action(str){
        document.getElementById("test1").innerHTML=str
    }
    </script>
</head>
<body>
    <form>
        <input type="radio" value="ping" name="rb" onclick="action(this.value)">Ping
        <input type="radio" value="card" name="rb" onclick="action(this.value)">Card
        <input type="radio" value="temp" name="rb" onclick="action(this.value)">Temprature
        <p id="test1">radio will be displayed here</p>
    </form>
</body>
</html>

当我移除表单时,它就起作用了。

更改函数action 的名称

试试这个:

<html>
<head>
<script type="text/javascript">
    function action123(str){
        document.getElementById("test1").innerHTML=str
    }
</script>
</head>
<body>
<form>
    <input type="radio" value="ping" name="rb" onclick="action123(this.value);">Ping
    <input type="radio" value="card" name="rb" onclick="action123(this.value);">Card
    <input type="radio" value="temp" name="rb" onclick="action123(this.value);">Temprature
    <p id="test1">radio will be displayed here</p>
</form>
</body>
</html>

您不应该再使用内联事件函数了。使用事件侦听器:

radios = document.getElementsByName("rb");
for(i=0; i<radios.length; i++) {
    radios[i].addEventListener('click', function(e){
       document.getElementById("test1").innerHTML = e.target.value;
    });
}

JSFiddle

"action"似乎是表单的阻塞名称空间

试试之类的东西

<script>   
function otherName(str){
document.getElementById("test1").innerHTML=str;
}
</script>
 <form name="form">
    <input type="radio" value="ping" name="rb" onclick="otherName(this.value)" />Ping
    <input type="radio" value="card" name="rb" onclick="otherName(this.value)" />Card
    <input type="radio" value="temp" name="rb" onclick="otherName(this.value)" />Temprature
<p id="test1">radio will be displayed here</p>
</form>

http://jsfiddle.net/waeqT/

最新更新