在jQuery中,为什么在点击未选中的复选框后,事件处理程序报告它未被检查? [英] In jQuery, why after a trigger of click on an unchecked checkbox, the event handler reports it is not checked?

查看:93
本文介绍了在jQuery中,为什么在点击未选中的复选框后,事件处理程序报告它未被检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将行为简化为最简单的情况(在最新的Chrome,Safari,Firefox,IE 9和10中测试过(jsfiddle在IE 8上不起作用)):

I can reduce the behavior to a simplest case (tested in the latest Chrome, Safari, Firefox, IE 9 and 10 (jsfiddle doesn't work on IE 8)):

http://jsfiddle.net/fjvqa/1

$("input").click(function (evt) {
    console.log("click event handler invoked", evt);
    console.log($("input").attr("checked"));
    console.log($("input").prop("checked"));
    console.log($("input").is(":checked"));
});

$("input").click();

包含HTML:

<input type="checkbox"></input>

输出为:

undefined
false
false

所以它是应该是正确的,它应该报告复选框没有被检查?

so is it supposed to be correct that it should report the checkbox is not checked?

如果它是正确的,那么为什么在jQuery 1.9.1中,行为完全相反? http://jsfiddle.net/fjvqa/2

If it is correct, then why in jQuery 1.9.1, the behavior is completely the opposite? http://jsfiddle.net/fjvqa/2

如果它不正确,我想知道为什么这样一个简单的错误仍然存​​在于2012年11月13日发布的jQuery 1.8.3中,这是大约4个月前...对于这样一个明显的错误?

If it isn't correct, I wonder why such a simple bug would be there still in jQuery 1.8.3, which was released Nov 13, 2012, which is just about 4 months ago... for such an obvious bug?

PS我明白不应该使用(1) attr()但是应该使用 prop()。我打印出来只是为了看看发生了什么。 (2)如果使用jQuery 1.8.3,更改处理程序实际上将报告与单击报告相反的情况: http://jsfiddle.net/fjvqa/3 如果是jQuery 1.9.1,他们会报告同样的事情: http://jsfiddle.net/fjvqa/4 我在寻找的是什么是真实的情况应该发生什么。

P.S. I do understand that (1) the attr() should not be used but prop() should be used instead. I print it out just to see what's happening. (2) the change handler actually will report the opposite of what click reports if using jQuery 1.8.3: http://jsfiddle.net/fjvqa/3 if it is jQuery 1.9.1, they report the same thing: http://jsfiddle.net/fjvqa/4 What I am looking for is what is the real situation of what is supposed to happen.

推荐答案

评论已经给出了答案 - 更改发生在点击之后。您绑定到使更改发生的事件。我猜你会看到版本之间的差异,因为对此没有明确的定义。解决方案是使用.change而不是.click:

Comments have given you the answer - the change happens AFTER the click. You're binding to an event that makes the change happen. I would guess you're seeing the discrepencies between the versions because there is no clear definition on this. The solution is to use .change instead of .click:

更新的小提琴:

http://jsfiddle.net/fjvqa/22/

$("input").change(function (evt) {
    console.log("click event handler invoked", evt);
    console.log($("input").attr("checked"));
    console.log($("input").prop("checked"));
    console.log($("input").is(":checked"));
});

$("input").click();

输出:

checked
true
true

这篇关于在jQuery中,为什么在点击未选中的复选框后,事件处理程序报告它未被检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆