有没有一种方法可以修改jQuery对象本身

Is there a way to modify a jQuery object itself?

本文关键字:修改 jQuery 对象 方法 一种 有没有      更新时间:2023-09-26

在jquery对象上使用.add.remove等函数时,jquery对象本身不会被修改,结果会被返回的新jquery对象捕获。

有没有办法修改对象本身?

我需要它,这样我就可以用引用传递的jQuery编写一个函数,比如这样的:

function DoThings(refJQuery) {
    refJQuery.find(...).remove(...);
    if (refJQuery.length > 0) {
        DoThings(refJQuery);
    }
}

重要提示:此代码示例只是对"通过引用传递的值"的用途/用法的提醒。

不,jQuery集合被设计为不可变的(您可以更改它们的属性,但您不应该这样做,它们是实现的一部分,而不是API)

当你想把一个不可变的对象传递给一个函数并对其进行修改时(假设获取返回值是不可行的),合成通常是一种方法。

通常,您应该使用自定义对象。但如果你愿意,你也可以设计一个通用的装饰器:

function MutableJQueryObject(jqo){
  this.jqo = jqo;
}
['add','find','filter',].forEach(function(k){
    MutableJQueryObject.prototype[k] = function(){
      this.jqo = $.fn[k].apply(this.jqo, arguments);
    }
});
['html','remove'].forEach(function(k){
    MutableJQueryObject.prototype[k] = function(){
      return this.jqo[k].apply(this.jqo, arguments);
    }
});
$.fn.mutable = function(){
  return new MutableJQueryObject(this);
}

因此,您将构建一个可变对象:

var $e = $('body').mutable();
console.log($e.html()); // html of the body
(function($c){
    $c.find('div'); // change the object
})($e);
console.log($e.html()); // html of the div