【问题标题】:Html checkBox onchange not workingHtml checkBox onchange不起作用
【发布时间】:2011-06-23 23:13:57
【问题描述】:
<input class="jProblemClass" id="Checkbox{%= ID %}" type="checkbox" onchange="problemPicker.onChangeProblemCheckBox('{%=ID %}');"/>

第一次选中或取消选中后,没有任何反应。在第二次点击后,调用我的函数problemPicker.onChangeProblemCheckBox,但我首先检查了 ID。为什么?谁能帮帮我?

onChangeProblemCheckBox: function(id) {
    if ($('#CheckBox' + id).attr("checked") == true) {
        problemPicker.addToCheckProblems(id);

        var checkboxes = $('.jProblemClass:checked');

        if ((checkboxes.length > general.limit) && (general.limit != 0)) {
            alert('The limit of ' + general.limit + ' problems exceeded. Please deselect ' + (checkboxes.length - general.limit).toString() + '.');
        }
    } else {
        problemPicker.delFromCheckProblems(id);
    }
},

【问题讨论】:

  • 你可能想向我们展示这个函数的作用——也许问题就在那里......

标签: jquery html checkbox onchange


【解决方案1】:

兄弟使用 onclick 事件而不是 onchange.. 原因... 根据我读过的 Javascript 参考资料, onchange 在 失去焦点。除非您单击其他地方,否则焦点不会在 IE 中丢失。 其他浏览器一定不能在等待焦点丢失之前 触发 onchange - 这表明他们没有正确遵循规范 (尽管在那个时候开火更有意义)。怎么用 onclick 和 onkeydown/onkeyup 代替(同时使用 onclick 和 onkeyup/onkeydown 你涵盖了鼠标和键盘的设置 复选框)。 参考:http://www.winvistatips.com/re-onchange-event-checkbox-not-working-properly-t311364.html

【讨论】:

    【解决方案2】:

    我认为,问题出在此处:$('#CheckBox' + id).attr("checked") == true。根据 HTML 规范,当此事件触发时,checked 应设置为 "checked"。因此,请尝试使用 $('#CheckBox' + id).attr("checked") == "checked" 甚至 $('#CheckBox' + id).attr("checked") 之类的内容。

    作为第二种选择,我建议您使用纯 jquery 来运行您的例程。例如,如果您有&lt;input type="checkbox" id="ac"&gt; 复选框,则可以使用此 jq 代码来处理您的例程:

    $(document).ready(function() {
        $("input[type=checkbox]").change(function() {
            alert("Am i checked? - " + $(this).attr("checked") + "\nMy ID:" + $(this).attr("id"));
        });
    });
    

    此案例显示在this demo

    【讨论】:

    • 在我在onclick 上更改事件onchange 后,一切正常。但如果我使用 onchange 没有任何效果。
    • 那么可能是 onchange 直到 onblur 触发才触发,选中该框后尝试将焦点设置在另一个元素上。
    • $('#CheckBox' + id).attr("checked") == true 是正确的代码。 $('#CheckBox' + id).attr("checked") == "checked" 对我不起作用。
    • 基本上,HTML 引用指定属性“checked”应设置为“checked”或不设置。但不同的浏览器可能会指定自己的数据。所以你最好检查一下这个属性是否存在:$('#CheckBox' + id).attr('checked') != null。不久前我意识到了这一点 =)
    【解决方案3】:

    尝试改用if($('#CheckBox' + id + ':checked').length &gt; 0),这样你就可以让jQuery找出复选框是否是checked

    此外,如果onChangeProblemCheckBox 使用problemPicker 中的任何内部属性,但没有使用完整路径引用它们,即problemPicker.nnnnn,它将失败,因为事件将在元素的上下文中触发,而不是在问题选择器中触发。就好像函数被这样调用$('#CheckBox' + id).onChangeProblemCheckBox()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多