繁体   English   中英

当单选值=“否”且未选择任何单选时,jQuery会识别页面加载时单选按钮的不正确状态

[英]jQuery recognising incorrect state of radio buttons on page load when radio value=“No” and neither radio is selected

我在页面上有单选按钮,可根据其状态在其他元素中添加或删除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()

暂无
暂无

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

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