jquery插件中return on的使用

use of return on in jquery plugin

本文关键字:on return 插件 jquery      更新时间:2023-09-26

我正在构建一个基本的jquery插件。这个插件工作得很好,即使没有在插件中使用return,但在jquery网站上,他们使用return来创建一个插件。所以我只是想知道什么是需要返回的插件。小提琴

$.fn.abc= function(options){    
     var settings = $.extend({
    // These are the defaults.
    width: "50px",
    borderLeft: "solid 1px #cecece"
    }, options );
    this.width(150)
    this.find('ul').each(function(i,elem){
        console.log(elem)       
        $(elem).css({width:settings.width})
    })      
}

return用于链接,您创建的插件不需要返回任何内容,但您可能想要创建两个将链接在一起的插件,您不返回任何内容,所以,

$('div').abc().css("background":"red");

不工作. .

关于你的问题,
var el= this.find('ul').each(function(i,elem){
    console.log(elem)       
    $(elem).css({width:settings.width})
});
return el;
http://jsfiddle.net/Nm93a/2/

这样我就可以返回所有元素而不是

 return this.find('ul').each(function(i,elem){
            console.log(elem)       
            $(elem).css({width:settings.width})
        });
http://jsfiddle.net/Nm93a/1/

这两个代码的工作原理相似,使用jquery的优点方法是编写更少的代码

,这些小的东西使jquery成为一个轻量级库

这是使用链接,没有返回你不能做这样的事情:

$('.element').hide().show().css({width:200}).animate({height:100}),

而不是每次都重写选择器

$('.element').hide();
$('.element').show();
$('.element').css({width:200});
$('.element').animate({height:100});

我想你的意思是

$.fn.plugin = function() {
    var settings = $.extend({
        width: '50'
    }, options);
    // return statement here?
    return this.find('ul').each(function(i, el){
        console.log(el);
    })
}

如果是,通过添加return,您允许链接。它返回传递给方法(可以进一步传递)的jQuery对象(带上下文)。

return用于在函数完成时返回值…假设我有一个非常基本的JavaScript函数:

addNums = function(value1, value2){
  return value1 + value2;
}

然后我要这样做:

alert( addNums(4, 4) );

将返回8,因为:

return value1 + value2;