Jquery返回值
我用了一个代码:
jQuery.fn.MyFunction = function(){ return this.each(function() { attributes = "test"; return attributes; });}
但是当我打电话时
var1 = $(this).MyFunction();alert(var1);
我有一个[对象],但不是“测试”。
如何让jquery插件返回一些值?
jQuery插件通常用于返回一个jQuery对象,因此您可以链接方法调用:
jQuery("test").method1().method2() ...
如果要返回其他内容,请使用以下语法:
jQuery.fn.extend({ myFunction: function( args ) { attributes = "test"; return attributes; } });
,或使用[]
通过索引访问它。
这是你的代码:
jQuery.fn.MyFunction = function() { #1 return this.each(function() { #2 return "abc"; #3 }); #4 }; #5
现在让我们检查每一行的作用。
- 我们声明属性
MyFunction
,它是每个jQuery对象的函数。 - 这一行是
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);
我相信jQuery返回对象,因此您可以保持不同函数的可链接性。
嗯,也许用
var1 = $(this)[0].MyFunction();alert(var1);
但我不确定这是否是您想要的,或者您的代码是否正常工作。 你想要达到什么目的? 你确定要调用this.each()
吗?
与其他人说的一样,jQuery在大多数情况下返回jQuery对象,并且可以使用indexer []
或get
方法来访问实际对象。