在jquery插件中使用return on

时间:2014-06-13 07:30:23

标签: javascript jquery

我正在jquery中构建一个基本插件。插件工作正常,即使不使用插件中的return,但在jquery网站上,他们使用return来创建插件。所以我只想知道插件中返回的需要是什么。 Fiddle

$.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})

    })      

}

4 个答案:

答案 0 :(得分:2)

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成为一个轻量级的库

答案 1 :(得分:1)

使用链接,没有返回,你不能做像:

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

相反,你每次都必须重写选择器

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

答案 2 :(得分:0)

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

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

然后我会做类似的事情:

alert( addNums(4, 4) );

这将返回8,因为:

return value1 + value2;

答案 3 :(得分:0)

我假设你的意思是

$.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对象(带有上下文)(可以进一步传递)。