[英]jQuery - calling function variable from another function variable
Why doesn't this work: 为什么这不起作用:
var foo = function() {
...
};
var boo = function() {
...
el.foo();
}
? ?
I get a foo is undefined error. 我得到一个foo是未定义的错误。 But I just defined it above...
但我刚刚在上面定义了......
You just need to call foo(), not el.foo(). 你只需要调用foo(),而不是el.foo()。 (Unless I'm missing something about how you're using this.)
(除非我遗漏了你如何使用它。)
Since foo is not a function defined/attached to el hence you can't call foo from el's context. 由于foo不是定义/附加到el的函数,因此您无法从el的上下文中调用foo。 You need to call foo directly.
你需要直接打电话给foo。
var foo = function() {
...
};
var boo = function() {
...
foo();
}
However if you need to call foo attached to el's context then try this: 但是如果你需要调用附加到el的上下文的foo,那么试试这个:
var boo = function() {
...
foo.call(el);//This calls foo in el's context
}
If I understand you correctly, you need to create a jQuery plugin function: 如果我理解正确,你需要创建一个jQuery插件函数:
jQuery.fn.foo = function(){
return this.each(function(){
// element-specific code here
});
};
var boo = function() {
...
el.foo();
}
Because foo
isn't a property of el
. 因为
foo
不是el
的财产。 It's a variable. 这是一个变量。
You'd need: 你需要:
var foo = function() {
//...
};
var boo = function() {
//...
foo();
}
It would work if you had: 如果你有:
var el = {};
el.foo = function() {
// ...
};
var boo = function() {
//...
el.foo();
}
In this instance it looks like foo()
is a not a property of the object el
. 在这个例子中,看起来
foo()
不是对象el
的属性。 You defined the function, but from the example shown, it is probably a global function. 您定义了该函数,但从显示的示例中,它可能是一个全局函数。 If you want
foo()
to work on the variable el
, then pass it to the function, like so: 如果你想让
foo()
处理变量el
,那么将它传递给函数,如下所示:
var foo = function(element) {
//do something with this element
};
var boo = function() {
...
foo(el); //pass el into the foo function so it can work on it.
}
I assume, if you are trying to call: 我想,如果你打算打电话:
el.foo()
Then el is jQuery object, something like 然后el是jQuery对象,类似于
var el = $("#smth");
el.foo();
In this case you need to define 'foo' as: 在这种情况下,您需要将'foo'定义为:
$.fn.foo = function() {
....
}
Otherwise, if you are just trying to call 'foo' from 'boo', then just call it without 'el': 否则,如果你只是试图从'boo'调用'foo',那么只需在没有'el'的情况下调用它:
var foo = function() {
...
};
var boo = function() {
...
foo();
}
Hope, it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.