不知道我是否直接看到有关包装方法的理论

发布于 2024-10-20 13:04:35 字数 415 浏览 4 评论 0原文

这是该理论的代码,

$.fn greenify = function(){
 return this.css ('color','green');
}

因此可以按如下方式使用

$('#today').greenify();

,该理论说:

“包装器方法必须始终返回原始集合,因此返回此。这样你可以在链中使用你的方法。”

对我来说,到目前为止我认为包装方法是一种定位多个 HTML 元素的方法。这是否仅仅意味着如果您定位这些元素,您实际上会获得这些目标 HTML 元素,因为它们是未经修改的?因此,当您说 return this 时,您想确认您确切地知道自己得到了什么,以便知道链接时使用的是什么?或者它有什么不同的含义吗?

Here's the code the piece of theory is about

$.fn greenify = function(){
 return this.css ('color','green');
}

so this can be used as follows

$('#today').greenify();

then, the theory says:

"A wrapper method must always return the original set, hence the return this. This way you can use your method in a chain."

To me, a wrapper method so far I saw as a way to target multiple HTML elements. Does it simply mean that if you target those elements, you actually get those targeted HTML elements just as they are, unmodified? So that when you say return this, you want to confirm you know exactly what you're getting so you know what you're using when you're chaining? Or does it mean something different?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若言繁花未落 2024-10-27 13:04:35

包装方法基本上意味着

对于任何选择器和任何方法
方法。 $(s).method() === $(s)

在你的情况下你想要

$.fn greenify = function(){
 return this.each(function() {
  this.css("color", "green");
 });
}

在这里你的方法修改集合中每个 dom 元素的颜色。并且您已经可以断言 this.each 作为 jQuery 对象 $(s) 上的方法将返回集合 $(s) 所以您的方法还会返回$(s)

当然,为了简单起见,您的函数会执行相同的操作,因为 $.fn.css 经过优化,可以在后台工作。为了清楚起见,我们自己调用 $.fn.each 而不是让 $.fn.css 为我们调用它。

A wrapper method basically means that

For any selector s and any method
method . $(s).method() === $(s)

In your case you want

$.fn greenify = function(){
 return this.each(function() {
  this.css("color", "green");
 });
}

Here your method modifies the colour of every dom element in the set. And you can already assert that this.each as a method on a jQuery object $(s) will return the set $(s) so your method also returns $(s).

Of course for simplicity sake your function does the same because $.fn.css is optimised to work on a set under the hood. For clarity were calling $.fn.each ourself rather then having $.fn.css call it for us.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文