Jquery返回值

Ant*_*ton 11 javascript jquery

我用了一个代码:

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

    return attributes;
});}
Run Code Online (Sandbox Code Playgroud)

但是当我打电话时

 var1 = $(this).MyFunction();alert(var1);
Run Code Online (Sandbox Code Playgroud)

我有一个[对象],但不是"测试".

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

Jus*_*ier 9

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

jQuery("test").method1().method2() ...
Run Code Online (Sandbox Code Playgroud)

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


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

            return attributes;
    }
});
Run Code Online (Sandbox Code Playgroud)

,或使用其索引访问它[].


Cro*_*zin 6

这是你的代码:

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

现在让我们检查每一行的作用.

  1. 我们声明属性MyFunction是每个jQuery对象的函数.
  2. 这一行是第一个也是最后一个声明jQuery.MyFunction().我们返回结果this.each(),而不是lambda函数的结果(用作参数jQuery.each()).并this.each()返回自己,所以最终的结果是你得到jQuery对象返回.

第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);
Run Code Online (Sandbox Code Playgroud)