2012-07-25 21 views
3

我正在使用jQuery Autocomplete来执行产品查找。我使用下面的代码从列表中选择执行:两个警示语句删除时仅基于存在几条警报语句的Javascript代码行为不同

$(".force-selection").blur(function(e) { 
    var value = $(this).val(); 
    //check if the input's value matches the selected item 
    alert($(this).val()); 
    alert($(this).data('selected-item')); 
    if(value != $(this).data('selected-item')) { 
    //they don't, the user must have typed something else 
    $(this) 
     .val('') //clear the input's text 
     .data('selected-item', ''); //clear the selected item 
    } 
}); 

上面的代码才会起作用。为什么行为只会根据一些警报声明而改变?

+1

比赛条件?在显示警告框时,也许还有其他事情正在发射? – Piskvor 2012-07-25 17:28:29

+1

您应该处理自动填充的[change](http://jqueryui.com/demosplete/#event-change)事件,而不是输入框“blur”事件。 – jbabey 2012-07-25 17:29:12

+1

自动完成查找是异步的。你将不得不等待那个,并且警报可以暂时停止你的代码。 – Bergi 2012-07-25 17:36:58

回答

2

尝试切换为使用Autocomplete change event而不是模糊事件。

  • 无论是作为创建自动完成时init选项:

    $(".selector").autocomplete({ 
        change: function(event, ui) { ... } 
    }); 
    
  • 或者类型来绑定change事件:autocompletechange。

    $(".selector").bind("autocompletechange", function(event, ui) { 
        ... 
    }); 
    
1

它可以通过几个问题引起的。

如果您使用的是Internet Explorer,alert将导致'模糊'事件触发您工作的任何字段。在示例代码中,很明显为什么会导致问题。否则,你可能正在寻找竞争条件问题。

看看这个小提琴的IE:http://jsfiddle.net/NsfKT/