关于 addEventListener 和 jquery的 $.on() 绑定自定义事件问题

如图:两种绑定方式图片描述

如图为浏览器内查看的事件绑定图片描述

目前看来 好像完全一样的绑定,但是只有jquery的绑定触发了,addEventListener 的绑定怎么也不能触发。
请大佬解惑~

阅读 18k
2 个回答

非原始事件,你在什么时候dispatch的?
使用jquery的dispatch在一个自定义事件,不会进入dom事件流程,进入的是jquery的事件流程,自然接收不到了。

eg:


var Events = {};
var nativeEvent = function(eventName) {
    return eventName === 'click';
}
var prototype = {
    on: function(eventName, handle) {
        if (nativeEvent(eventName)) {
            this.dom.addEventListener(eventName, handle);
        } else {
          Events[eventName] = {
            ctx: this,
            handle
          };
        }
        
    },
    fire: function(eventName, args) {
        var eventObject = Events[eventName];
        eventObject.handle.call(eventObject.ctx, args);
    }
};
var jquery = function(selector) {
    if( !(this instanceof jquery)) {
        return new jquery(selector);
    }
    this.dom = document.querySelector(selector);
    
};

jquery.prototype = prototype;
 
var dest = jquery('#wrapper');

dest.on('click', function(e) {console.log(e);});

dest.on('custom', function(e) {console.log(e);});

dest.fire('custom', {data: 'somedata'}); //需要主动派发,或者bind到某个native事件

就用你写的方式我特意测试了一遍,没发现问题。
jquery用on代理绑定。
代码:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Test</title>
</head>
<body>

<button id="btn">TEST</button>

<script src="jquery.js"></script>
<script>

    $("body").on('click', '#btn', function(){
        console.log("jquery click");
    });

    document.getElementById("btn").addEventListener('click', function(){
        console.log("javascript click");
    })
    
</script>
</body>

</html>

结果:

clipboard.png

怀疑是你的 ifChecked 事件的问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题