[英]Is is possible to scope the jquery selector
我想对jquery对象进行作用域,以便可以覆盖作用域内的已添加函数,而无需更改在其他任何地方仍在使用的函数。
这是我想做的事的一个例子,但它没有按预期工作。 有人可以帮忙吗?
$.fn.method = function(){
alert("old method");
}
(function ($) {
//I want to scope functions to jquery in here
$.fn.method = function(){
alert("new Method")
}
$("#MyId").method(); //should alert NEW method | WORKS CORRECTLY!
})(jQuery)
$("#MyId").method(); //should alert OLD method | DOES NOT WORK CORRECTLY
是的,只需将所有内容复制到新的obj中就可以实现:
{
const fakeJquery = (...args) => jQuery(...args);
Object.assign(fakeJquery, jQuery);
fakeJquery.fn = {};
(function ($) {
$.fn.method = function(){
alert("new Method")
}
$("#MyId").method();
})(fakeJquery)
}
一种方法是将方法保存在变量中,并在使用“ New method”完成操作后将其还原
$.fn.method = function(){
alert("old method");
};
(function ($) {
//save method we are about to over write
var x = $.fn.method;
$.fn.method = function(){
alert("new Method");
};
$("#MyId").method(); //should alert NEW method | WORKS CORRECTLY!
//Restore method we over wrote
$.fn.method = x;
})(jQuery);
$("#MyId").method(); //now alerts OLD method | WORKS CORRECTLY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.