开发者

Don't know if i'm seeing theory about wrapper method straight

开发者 https://www.devze.com 2023-02-15 06:30 出处:网络
Here\'s the code the piece of theory is about $.fn greenify = function(){ return this.css (\'color\',\'green\');

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号