【问题标题】:Change event precedence with JQuery使用 JQuery 更改事件优先级
【发布时间】:2011-12-29 09:41:49
【问题描述】:

我有以下html代码:

<input type="text" id="theInput" value=""/>     
<a href="#" id="theLink">Click me</a>

我想检测输入何时更改并在这种情况下执行操作,但仅当用户没有单击链接时。我试过这个:

$('#theLink').live('click', function(){
  alert('click');
});

$('#theInput').live('change', function(){
  alert('change');
});

但是,由于 Javascript 事件优先规则,当输入中的值发生更改时,change 始终在 click 之前执行,因此仅显示“更改”消息。

我希望它仅在输入值更改并且用户在任何其他位置而不是链接单击退出输入时才显示change。在最后一种情况下,我想显示click

例子是here

我使用 jQuery 1.6.4。

【问题讨论】:

  • 好问题!我对这里的答案很感兴趣...
  • 我更新了我的答案,我终于明白你的问题了

标签: javascript jquery html events javascript-events


【解决方案1】:

据我所知,click 事件在每个浏览器中的blurchange 事件之后触发(请查看this JSFiddle)。 blurchange 的顺序因浏览器而异(来源:Nicholas Zakas)。

要解决您的问题,您可以在文档上监听click 事件并将事件的目标与#theLink 进行比较。任何点击事件都会冒泡到文档中(除非它被阻止)。

试试这个:

var lastValue = '';

$(document).click(function(event) {
    var newValue = $('#theInput').val();

    if ($(event.target).is('#theLink')) {
        // The link was clicked
    } else if (newValue !== lastValue) {
        // Something else was clicked & input has changed
    } else {
        // Something else was clicked but input didn't change
    }

    lastValue  = newValue;
});

JSFiddle:http://jsfiddle.net/PPvG/TTwEG/

【讨论】:

  • 似乎可以工作,但是在捕获页面中的所有click 事件时,我有点担心性能。
  • @Pablo:用户点击的次数会不会产生明显的不同?
  • 好的,我终于选择了与您的解决方案类似的东西。非常感谢你。最终解决方案 JSFiddle 是 here,以防它对任何人有所帮助。
【解决方案2】:

这两个事件都会触发,但在您的示例中,onmousedown 事件发生时触发的onchange 事件处理程序中的警报将停止触发onclick 事件所需的onmouseup 事件。使用 console.log 将显示这两个事件触发。

http://jsfiddle.net/hTqNr/4/

【讨论】:

    【解决方案3】:

    好的,我知道了,你可以做

    $('#theLink').live('click', function(e){
        alert('click');
    });
    
    $('#theInput').live('change', function(e){
        //Check if the change events is triggerede by the link
        if(e.originalEvent.explicitOriginalTarget.data === "Click me"){
             //if this is the case trigger the click event of the link
             $('#theLink').trigger("click");
        }else{
            //otherwise do what you would do in the change handler
            alert('change');
        }
    });
    

    在这里提琴http://jsfiddle.net/hTqNr/19/

    【讨论】:

    • 感谢您的回答。但是,我收到一个错误:Cannot read property 'data' of undefined
    • 好的,现在我明白了。上一个错误在使用 Chrome 浏览器时发生,但适用于 Firefox。
    • 这是一个不错的解决方案,但仅适用于基于 Gecko 的浏览器。来源:MDN
    【解决方案4】:

    为什么不选择输入框的值。您必须将输入框的初始值存储在就绪函数中

     initialvalue= $('#theInput').val();
    

    然后比较值

     $('#theLink').live('click', function(){
        var newvalue =$('#theInput').val();
            if(newvalue!=initialvalue) {
                //do something
             }
    
      });
    

    【讨论】:

    • 使用您的代码,当值更改并且用户在链接外部单击时,我没有收到change 消息。此外,我想要的是当用户点击链接时,我不关心值的变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多