jQuery识别页面加载上的单选按钮的不正确状态,当单选值=“0”时;否”;并且两个无线电都没有被选择

jQuery recognising incorrect state of radio buttons on page load when radio value="No" and neither radio is selected

本文关键字:两个 选择 无线电 识别 不正确 状态 单选按钮 加载 jQuery 单选值      更新时间:2023-09-26

我在页面上有单选按钮,可以根据其他元素的状态添加或删除css类。

testclass默认添加到元素slave(即页面加载的HTML为:

<input type="radio" value="No" name="master" /> No
<input type="radio" value="Yes" name="master" /> Yes
<input type="text" name="a" id="slave" class="testclass" />

如果选择了"否"无线电,下面的jQuery将删除该类

$("input[name$='master']").change(function(){
    if(this.value === 'No') {
          $('#slave').removeClass('testclass'); 
    } else {
         $('#slave').addClass('testclass');
    }
}); $("input[name$='master']").filter(':checked').change()

页面加载后,在状态之间来回移动可以很好地工作,但我在页面加载时触发了该功能,并且当没有选择复选框时,它会删除类。(如果"是"加载为选中状态,则可以)。

有趣的是,如果我反转条件,要求"是"来删除类(页面加载时类仍然存在),也可以

我认为javascript可能将未进行的选择等同于值"否",因此我尝试了严格的等式,但没有区别。

有什么想法吗?

我开发了一把小提琴供您考虑。这是它的链接=>http://jsfiddle.net/6c7F2/

我认为回答这个问题的最好方法是让你了解关于你在这里提供的代码的一些事情。我会写评论给它。

$( document ).ready(function(){ // this function is called once your page loads
    $("input[name$='master']").change(function(){
        //this function is not called until you click the radio buttons. 
        // Be careful to note that this function is never called on page load. 
        // You can test it in the fiddle I created
        if(this.value === 'No') {
            $('#slave').removeClass('testclass'); 
            // this alert in the fiddle is called only
            // when you click the radio buttons. Not on page load
            alert("It entered");
        } else {
            $('#slave').addClass('testclass');
        }
    }); 
    $("input[name$='master']").filter(':checked').change()
});

因此,请确保要在页面加载上执行的内容和检查应该在$("input[name$='master']").change(function(){}); 的范围之外

只有当您单击单选按钮而不是页面加载时才会触发此操作。

之所以发生这种情况,是因为您在页面加载时没有选择任何值,但仍在触发事件。

尝试:

默认情况下,选中任意复选框。

<input type="radio" value="No" name="radios" checked="checked"/> No

删除该行

$("input[name$='master']").filter(':checked').change()