【问题标题】:jQuery - Error when combining <select> and checkboxjQuery - 组合 <select> 和复选框时出错
【发布时间】:2014-04-18 18:13:45
【问题描述】:

好的,这段代码创建了一个&lt;select&gt; 和一个复选框:

<select id="sel" size="2" onChange="onChange();">
    <option>check</option>
    <option>uncheck</option>
</select>
<input id="cb" type="checkbox"></input>

这是我的onChange(),当&lt;select&gt; 的值发生变化时会调用它:

function onChange() {
    // Get the value of the currently selected option.
    var selected = $('#sel').find(":selected").text();
    // Check the box if "check" was selected, otherwise uncheck it.
    $("#cb").attr('checked', selected == 'check'); 
}

现在,这工作正常一次。假设我按以下顺序选择选项:

  1. "check" > 复选框检查
  2. “取消选中”> 取消选中复选框
  3. "check" > 复选框不选中

那么是我的代码有问题还是我发现了 jQuery 中的故障?

这是我的JSFiddle的链接

【问题讨论】:

  • 当我使用小提琴时,它根本不起作用

标签: jquery html select checkbox


【解决方案1】:

为了更干净。我从标记中删除了 onchange 处理程序,其余的由 jquery 处理。 您的主要问题是您使用 attr 而不是 prop

http://jsfiddle.net/M8Qw7/8/

JS

$('#sel').on('change', function() {
    var selected = $(this).find(":selected").text(); // Get the currently selected option's text value.
    $("#cb").prop('checked', selected == 'check'); // Check the box if option "check" was selected.
});

HTML

<select id="sel">
    <option>check</option>
    <option>uncheck</option>
</select>
<input id="cb" type="checkbox"></input>

【讨论】:

    【解决方案2】:

    将 attr 更改为 prop 即可使用 gr8!

    代码如下:

    function onChange() {
        var selected = $('#sel').find(":selected").text(); // Get the currently selected option's text value.
        $("#cb").prop('checked', selected == 'check'); // Check the box if option "check" was selected.
    }
    

    JSFiddle

    【讨论】:

    • 谢谢!像魅力一样工作。
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多