Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

javascript - Jquery dispatchEvent wrapper method

Is there a wrapper method or some library for dispatchEvent in jquery? I've been looking for this on stackoverflow, but the closest method I've found is jquery's trigger(), which appears to only trigger jquery event listeners. Of course I could just use dispatchEvent myself, but I want to use jquery to make my code easier to read.

I'm writing a greasemonkey script, where I want to fire an event to some anonymous event listener. The page itself is not written in jquery.

Here's a jsfiddle link to explain what I'm trying to accomplish: https://jsfiddle.net/Zx3CA/

js:

function log(s){
    document.getElementById('log').innerHTML+=s+'<br/>';
}

$(function(){
    //code on the page, which shouldn't be changed
    //start
    document.getElementById('link').addEventListener('click',function(){
        log('click detected');
    },false);
    //end
    
    $('#triggerClickJQuery').on('click',function(){
        $('#link').trigger('click');
    });
    
    $('#triggerClickJS').on('click',function(){
        var event=document.createEvent('MouseEvents');
        event.initMouseEvent('click',true,true,null,-1,-1,-1,-1,0,true,false,false,true,0,null);
        $('#link').get(0).dispatchEvent(event);
    });
});

html:

<body>

<a id="link" href="javascript:void(0);">Link</a><br/>
<a id="triggerClickJQuery" href="javascript:void(0);">Trigger Click JQuery</a><br/>
<a id="triggerClickJS" href="javascript:void(0);">Trigger Click JavaScript</a><br/>

<div id="log"></div>

</body>

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The implementation of trigger in jQuery (upto 1.10.1) for custom events doesn't fire a native event and therefore you wont be able to listen for it via addEventListener or a different version of jQuery loaded on the same page.

This bug with all of its use-cases is well documented here: http://bugs.jquery.com/ticket/11047

As a solution you can use this plugin, which checks if the browser supports firing custom native events and uses it when available.

https://github.com/sandeep45/betterTrigger


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...