【问题标题】:jQuery mouseup event not detecting checked attribute?jQuery mouseup 事件未检测到选中的属性?
【发布时间】:2015-01-07 19:12:10
【问题描述】:

我正在尝试监视 mousedown() 和 mouseup() 上复选框的“已选中”属性的任何更改,但似乎有问题。 mousedown 事件正在注册复选框的正确状态(选中或未选中),但 mouseup 事件正在反向注册这些状态。

如果在 mouseup 上选中复选框,则 mouseup 事件表示未选中,如果在 mouseup 上未选中复选框,则事件表示已选中。有什么想法吗?

以下是相关代码:

$('.input-wrapper input[type=checkbox]').mousedown(function() {

    console.log('===== MOUSEDOWN =====');

    if (this.checked) {
        console.log('The checkbox already had the "checked" attribute on mousedown');
    }
    if (!this.checked) {
        console.log('The checkbox did NOT have the "checked" attribute on mousedown');
    }

    console.log('\n\n');

}).mouseup(function() {

    console.log('===== MOUSEUP =====');

    if (this.checked) {
        console.log('The checkbox was assigned the "checked" attribute on mouseup');
    }
    if (!this.checked) {
        console.log('The checkbox\'s "checked" attribute was removed on mouseup');
    }

    console.log('\n\n');

});

...

我还在 jsFiddle 上设置了一个演示,here

【问题讨论】:

  • 很确定 mouseup 在检查更改之前会触发
  • 我担心这就是正在发生的事情......你认为有什么办法可以解决这个问题吗?
  • 好吧,你可以改变鼠标上移的顺序 console.log
  • 这很简单,只需禁用它,用户就无法对其进行任何操作。在问题中提供您的问题的完整详细信息,这是一个 X-Y 问题
  • @Amygdala 推理很重要,因为您解决更高级别问题的方法不起作用,但从未提及更高级别的问题。因此,这是一个X-Y problem 请对那些试图帮助你的人更加尊重

标签: javascript jquery checkbox mouseevent checked


【解决方案1】:

问题是鼠标在控件实际更改之前运行。

例如。框未选中然后单击

鼠标按下 - this.checked 为假

mouse up - this.checked 仍然是 false,因为控件实际上并没有改变。

this.checked 直到鼠标向上运行后才会更新。

【讨论】:

  • 感谢您对所提问题的真实回答。
  • 感谢投票。当我输入我的答案时,当他的评论进来时,一定要让 juvian 起来。
【解决方案2】:

jQuery 提供了一个非常有趣的方法,称为.change,每次选中或取消选中复选框时都会触发该方法。

$('.input-wrapper input[type=checkbox]').change(function() {

    if (this.checked) {
        // do this
    } else {
        // do that
    }
});

参见 JSFiddle:http://jsfiddle.net/ayj1o9dc/3/

【讨论】:

  • 因为“更改”仅适用于复选框更改状态之后...我需要能够在允许状态更改之前判断是否已满足限制。
  • 但是@Amygdala 你可以防止Default() ...需要更清楚你的目标
  • @Amygdala 如果不符合限制,请使用$(this).attr('checked', false);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多