Javascript Jquery返回值
我使用了一个代码:Javascript Jquery返回值,javascript,jquery,Javascript,Jquery,我使用了一个代码: jQuery.fn.MyFunction = function(){ return this.each(function() { attributes = "test"; return attributes; });} 但是当我打电话的时候 var1 = $(this).MyFunction();alert(var1); 我得到了一个[对象],但不是“测试” 如何允许jquery插件返回某个值?我相信jquery会返回对象,因此您可以保持不同函数的可链
jQuery.fn.MyFunction = function(){
return this.each(function() {
attributes = "test";
return attributes;
});}
但是当我打电话的时候
var1 = $(this).MyFunction();alert(var1);
我得到了一个[对象],但不是“测试”
如何允许jquery插件返回某个值?我相信jquery会返回对象,因此您可以保持不同函数的可链接性。jquery插件通常设计为返回jquery对象,以便您可以链接方法调用:
jQuery("test").method1().method2() ...
如果要返回其他内容,请使用以下语法:
jQuery.fn.extend({
myFunction: function( args ) {
attributes = "test";
return attributes;
}
});
,或者使用[]
Hmm通过其索引访问它,或者使用
var1 = $(this)[0].MyFunction();alert(var1);
但我不确定这是否是您想要的,或者您的代码是否有效。你想达到什么目标?是否确实要调用this.each()
正如其他人所说,在大多数情况下,jQuery返回jQuery对象,可以使用索引器
[]
或get
方法来访问实际对象。下面是您的代码:
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对象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);
不知道您可以为此使用get方法-您可以发布一个示例吗?例如,您可以编写
$(“.someClass”).get(0)代码>。还是我弄错了?谢谢,语法“jQuery.fn.extend”帮助了我。另外,你回答时忘了“fn”。接得好,谢谢!我在查看jQuery源代码中的isArray示例,但是忘记了isArray是一个不需要fn的“静态”调用,您只是返回传递给每个
的函数,而不是返回MyFunction
扩展名。您的第二个示例应该是公认的答案,因为它更简洁明了。