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插件返回一些值?
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)
,或使用其索引访问它[]
.
这是你的代码:
jQuery.fn.MyFunction = function() { #1
return this.each(function() { #2
return "abc"; #3
}); #4
}; #5
Run Code Online (Sandbox Code Playgroud)
现在让我们检查每一行的作用.
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);
Run Code Online (Sandbox Code Playgroud)