简体   繁体   English

onmouseover检查输入单选按钮,仅javascript

[英]onmouseover check a input radio button javascript only

Instead of clicking on a radio button, how can we create a onmouseover event and javascript to make the radio button checked when simply hovering onto it? 除了单击单选按钮以外,我们如何创建onmouseover事件和javascript,只需将鼠标悬停在其上,即可checked该单选按钮? Please no jQuery. 请不要jQuery。

 <input type="radio" class="tryout" name="example" onmouseover="checkButton()" checked="checked"> <input type="radio" class="tryout" name="example" onmouseover="checkButton()"> <input type="radio" class="tryout" name="example" onmouseover="checkButton()"> <input type="radio" class="tryout" name="example" onmouseover="checkButton()"> 

You would have the checkButton function pass in the element as the parameter then set the element.checked to true. 您可以将checkButton函数作为参数传递给元素,然后将element.checked设置为true。 For example: 例如:

 function checkButton(element){ element.checked = true; } 
 <input type="radio" class="tryout" name="example" onmouseover="checkButton(this)" checked="check"> <input type="radio" class="tryout" name="example" onmouseover="checkButton(this)"> <input type="radio" class="tryout" name="example" onmouseover="checkButton(this)"> <input type="radio" class="tryout" name="example" onmouseover="checkButton(this)"> 

I would even add to what jakekimds did and avoid putting your javascript inline on your inputs to separate presentation and functionality. 我什至会添加jakekimds所做的事情,并避免将您的javascript内联在输入上,以分开显示和功能。 So you would get 所以你会得到

HTML 的HTML

<input type="radio" class="tryout" name="example1">
<input type="radio" class="tryout" name="example2">
<input type="radio" class="tryout" name="example3">
<input type="radio" class="tryout" name="example4">

JS JS

var inputs = document.getElementsByClassName('tryout');
[].forEach.call(inputs, function(el){
    el.addEventListener('mouseenter',function(){
        this.checked = true;
    });
});

If you wrap the radio buttons in a container, you can then use document.getElementById to attach an event handler. 如果将单选按钮包装在容器中,则可以使用document.getElementById附加事件处理程序。 That way, if your JavaScript changes, your HTML doesn't. 这样,如果您的JavaScript更改了,您的HTML不会更改。

<span id="radio-buttons">
    <input type="radio" class="tryout" name="example" checked="check">
    <input type="radio" class="tryout" name="example">
    <input type="radio" class="tryout" name="example">
    <input type="radio" class="tryout" name="example">
</span>
<script>
document.getElementById("radio-buttons").onmouseover = function (e) {
    e.target.checked = true;
}
</script>

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

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