jQuery $ el.trigger('change')不会触发本机侦听器

时间:2014-01-22 18:16:44

标签: javascript jquery onchange dom-events

考虑以下HTML:

<select value="val2">
  <option value="val1">o1</option>
  <option value="val2">o2</option>
</select>

和JavaScript(在文档就绪时执行):

var $select = $('select');
var select = $select.get(0);

function logger(msg) {
    return function () { console.log(msg); };
}

$select.on('change', logger('jquery on select'));
$(document).on('change', logger('jquery on document'));

select.addEventListener('change', logger('native on select'), false);
document.addEventListener('change', logger('native on document'), false);

setTimeout(function () {
    console.log(' == programmatic ==');
    $select.trigger('change');
    console.log(' == now try manual ==');
}, 1000);

这导致控制台中的以下输出:

 == programmatic ==
jquery on select
jquery on document
 == now try manual ==
jquery on select
native on select
jquery on document
native on document 

问题是:为什么没有调用本机绑定的侦听器?如何让他们被召唤?

这里也是一个jsFiddle:http://jsfiddle.net/PVJcf/

(使用jQuery 2.0.2)

1 个答案:

答案 0 :(得分:22)

本文概述了该主题:

<强> Triggering Event Handlers

基本上,trigger只会触发通过jQuery附加的事件处理程序或html中的某些事件处理程序属性。

您可以定义一个插件来触发本机浏览器事件,如下所示:

(function($) {

    $.fn.trigger2 = function(eventName) {
        return this.each(function() {
            var el = $(this).get(0);
            triggerNativeEvent(el, eventName);
        });
    };

    function triggerNativeEvent(el, eventName){
      if (el.fireEvent) { // < IE9
        (el.fireEvent('on' + eventName));
      } else {
        var evt = document.createEvent('Events');
        evt.initEvent(eventName, true, false);
        el.dispatchEvent(evt);
      }
}

}(jQuery)); 

// sample usage
$('select').trigger2('change');

这不完美,但应该给你一般的想法。

Here's an update to your fiddle using this plugin.