trying to map someFunction.jQuery to “$”

泪湿孤枕 提交于 2019-12-25 05:43:25

问题


I found a function (via this person's github) that I might use in my script that mimics the functionality of an API object.

Here's the relevant code from the link:

unsafeWindow = (function() {
    var e1 = document.createElement('p')
    e1.setAttribute('onclick', 'return window;');
    return e1.onclick();
})();

Where the poster says you can use the function in the format unsafeWindow.jQuery

Now, I want to be able to use $ instead of the jQuery keyword elsewhere in my code. I tried learning from this stack overflow question to simplify it and re-wrote the code like so:

(function($){
    var e1 = document.createElement('p')
    e1.setAttribute('onclick', 'return window;');
    return e1.onclick();
})(jQuery);

But it didn't work. I guess I could just try something like $ = unsafeWindow.jQuery in order to map to the $, but I wanted to try to do it in the format seen above.


回答1:


You would map $ to unsafeWindow.jQuery like so:

unsafeWindow    = ( function () {
    var dummyElem   = document.createElement('p');
    dummyElem.setAttribute ('onclick', 'return window;');
    return dummyElem.onclick ();
} ) ();

var $ = unsafeWindow.jQuery;

// Now you can use the page's jQuery. EG:
$("body").append ('<p>Content added by unsafeWindow.jQuery</p>');


But keep in mind:

  1. This is a Hack, and it will probably stop working around Chrome version 28.

  2. It may still fail due to a race condition about when userscripts fire. To fix that, add // @run-at document-end to the userscript's metadata block.

  3. Don't do things this way! It will only cause grief, side effects and maintenance headaches.

    For userscripts: use this technique (best cross-browser)  or  this technique (relies on page's jQuery, but the example shows how to use GM_ functions too).

    For full extensions or content scripts:, use this technique (use the manifest.json and keep everything properly sandboxed).



来源:https://stackoverflow.com/questions/16071590/trying-to-map-somefunction-jquery-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!