在jQuery中,为什么程序化地触发“click()”在一个复选框不立即检查呢? [英] In jQuery, why does programmatically triggering 'click()' on a checkbox not immediately check it?

查看:95
本文介绍了在jQuery中,为什么程序化地触发“click()”在一个复选框不立即检查呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:这仅适用于jQuery 1.8及以下版本。这是在jQuery 1.9中修复的问题

以下是我最小的jsfiddle示例: http://jsfiddle.net / 8fuEJ /

Here is my minimal jsfiddle example: http://jsfiddle.net/8fuEJ/. I'm using Google Chrome, if that makes a difference.

我有一个复选框:

<input type="checkbox" id="wtf">

我有一个jquery事件处理程序:

And I have a jquery event handler:

$('#wtf').click(function(ev) { alert(this.checked); });

到目前为止,还不错。当我单击复选框,我首先看到复选标记出现,然后警报真(按该顺序)。当我再次点击它时,我看到复选标记消失,然后是警告假。

So far, so good. When I click the checkbox, I first see the checkmark appear, then the alert "true" (in that order). When I click it again, I see the checkmark disappear, then the alert "false".

问题出现在我以编程方式触发点击事件。像这样:

The problem comes when I programmatically trigger the click event. Like this:

$('#wtf').click(function(ev) { alert(this.checked); });
$('#wtf').click();

在这种情况下,首先我看到警报false(复选标记仍然不可见)

In this case, first I see the alert "false" (with the checkmark still not visible), then after dismissing the alert, the checkmark appears.

为什么会有这样的区别?

Why the difference in order here?

还要注意,如果我使用事件处理程序 change ,它会按预期工作。

Also note that if I use the event handler change, it works as expected.

$('#wtf').change(function(ev) { alert(this.checked); });
$('#wtf').click();

在这里,我看到复选标记,然后是警报true。

Here, I see the checkmark appear, then the alert "true".

推荐答案

这里有三种类型的动作:

There are three types of actions going on here:


  1. 手动单击它将更改状态。这就是它本身;触发器然后触发,因为它意识到它已被点击。

  2. 调用 Click()事件首先调用javascript事件。 jQuery优先处理您提供的函数,因为它可能很好地取消该点击或执行一些其他操作。完成后,javascript会更改复选框的状态。

  3. 最后,更改()事件模仿手动点击浏览器点击它。

  1. Manually clicking it changes the state. That is all it does by itself; the trigger then fires because it is realizing that it has been clicked. This is a matter of browser behavior before scripting behavior.
  2. Calling the Click() event calls the javascript event first. jQuery prioritizes the function you provided, as it may very well cancel that click or perform some other action. After that is completed, javascript changes the status of the checkbox.
  3. Lastly the Change() event is mimicking the manual clicking by telling the browser to click it. That means that the item is being changed by the browser, which then in turn is calling your triggered event.

基本上,区别在于,浏览器会改变项目, Click()是一个直接的JavaScript调用。它可以做别人不能做的事情,例如取消变化,做各种其他的东西,所以它是延迟的状态的改变,只要它可以。

Essentially the difference is that the Click() is a straight javascript call. It can do things the others cannot, such as cancel the change and do all sorts of other zany stuff, so it is delaying the change of state for as long as it can.

这篇关于在jQuery中,为什么程序化地触发“click()”在一个复选框不立即检查呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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