Jquery返回值

时间:2010-03-13 14:35:04

标签: javascript jquery

我使用了代码:

jQuery.fn.MyFunction = function(){
return this.each(function() {
    attributes = "test";

    return attributes;
});}

但是当我打电话时

 var1 = $(this).MyFunction();alert(var1);

我有[对象],但没有“测试”。

如何让jquery插件返回一些值?

4 个答案:

答案 0 :(得分:9)

jQuery插件通常用于返回一个jQuery对象,因此您可以链接方法调用:

jQuery("test").method1().method2() ...

如果要返回其他内容,请使用以下语法:


jQuery.fn.extend({
    myFunction: function( args ) {
            attributes = "test";

            return attributes;
    }
});

,或使用[]通过索引访问它。

答案 1 :(得分:6)

这是你的代码:

jQuery.fn.MyFunction = function() { #1
   return this.each(function() {    #2
      return "abc";                 #3
   });                              #4
};                                  #5

现在让我们检查一下每行做什么。

  1. 我们声明属性MyFunction,它是每个jQuery对象的函数。
  2. 此行是jQuery.MyFunction()的第一个和最后一个声明。我们返回 this.each()的结果,而不是lambda函数的结果(用作jQuery.each()的参数)。并且this.each()返回自身,因此最终结果是返回了jQuery对象。
  3. 第3-5行实际上并不重要。

    请考虑这两个例子:

    jQuery.fn.MyFunction = function() {
        return this.each(function() {
            return "abc";
        });
    };
    
    jQuery.fn.AnotherFunction = function() {
        return "Hello World";
    };
    
    var MyFunctionResult = $(document).MyFunction();
    var AnotherFunctionResult = $(document).AnotherFunction();
    
    alert(MyFunctionResult);
    alert(AnotherFunctionResult);
    

答案 2 :(得分:1)

我相信jQuery会返回对象,因此您可以保持不同函数的可链接性。

答案 3 :(得分:0)

嗯,也许用

var1 = $(this)[0].MyFunction();alert(var1);

但我不确定这是不是你想要的,或者你的代码是否适用。你想要实现什么目标?您确定要拨打this.each()吗?

与其他人一样,jQuery在大多数情况下返回jQuery对象,并且可以使用索引器[]get方法来访问实际对象。