gpt4 book ai didi

javascript - 如何将选定的元素传递给链式函数中的 'this'

转载 作者:行者123 更新时间:2023-11-28 18:39:39 25 4
gpt4 key购买 nike

我试图了解链式函数如何工作,特别是如何将选定的元素传递给链式函数。

假设我们有一个链式函数,如下所示:

var func = {};
func.remove= function() {
$(this).remove();
}

如何通过 jQuery 或 JavaScript 选择一个元素并将其传递给链式函数,如下所示:

var elm = $("foo");
elm.func.remove();

或者

var elm2 = document.getElementById("foo");
elm2.func.remove();

最佳答案

链式函数是一种返回所调用对象的方法(因此它不能返回元素本身,除非您扩展 native DOM 对象,但不建议这样做)。

func 没有被链接,因为它根本不是一个函数。 remove 在不返回其所属对象之前不会被链接。

如果您想要执行与元素一起使用的链式函数,那么您需要定义一个对象,在该对象上定义链式方法,并将该元素存储为该对象的属性。

例如:

function MyConstructor(element) {
this._element = element;
}

MyConstructor.prototype.doA = function doA () {
console.log(this._element);
return this;
};

MyConstructor.prototype.doB = function doB () {
element.style.display = "none";
return this;
};

var example = new MyConstructor(document.getElementById('foo'));
example.doA().doB();

关于javascript - 如何将选定的元素传递给链式函数中的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com