关于范围的问题 - jQuery
我有这个函数,它具有这段代码(为了简洁而编辑):
(function ($) {
// mouseenter event for each menu item
$menuItems.bind('mouseenter', function (e) {});
})(jQuery);
我想做的是从其他函数中的这个函数访问 $menuItems 。
例如:
$("#products a").click(function(){
$menuItems.unbind("mouseenter");
});
我认为这是一个范围问题?
我不确定该怎么做?
I have this function which features this bit of code (edited for succinctness):
(function ($) {
// mouseenter event for each menu item
$menuItems.bind('mouseenter', function (e) {});
})(jQuery);
What I would like to do is access $menuItems from this function in other functions.
For example:
$("#products a").click(function(){
$menuItems.unbind("mouseenter");
});
I believe this is a matter of scope?
I'm unsure how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第三种选择:
A third option:
在您的代码之前添加
它应该可以工作。顺便说一句,你的代码中有解析错误,你丢失了
(所以它看起来像)
before your code, add
and it should work. Btw you've got parse error in your code, you're missing
(so it would look like)
您必须在全局命名空间中声明 $menuItems,字面意思如下:
您的 IDE 可能会抱怨 $menuItems 未定义,但对于 javascript 来说它会定义。
就作用域而言,如果您有一个函数或匿名方法,并且里面有这样一行:
var myVar = SomethingElse;
那么作用域定义 myVar 是只有该函数或方法内的其他任何东西都知道。
如果您将声明放在函数体之外,那么它将可用于任何可用的函数/方法。
至于最佳实践,这可能并不总是一件好事,它类似于使用全局变量并听取 comp.sci 教授的意见,但如果您知道代码的范围并且对命名约定很敏感,那么您的名字就不会被忽略。和其他东西不冲突,一般都可以。
You would have to declare $menuItems in the global namespace, literally like so as an example:
Your IDE might complain that $menuItems isn't defined, but to javascript it would be.
As far as scope is concerned, if you have a function or anonymous method, and have a line like this inside it:
var myVar = somethingElse;
then scope defines that myVar is only known to anything else inside that function or method.
If you put your declaration outside of the body of a function then it will be available to any function/method that is available.
As for best practices, this may not always be a good thing, it's similar to using globals and listening to your comp.sci professor, but if you know the scope of your code and are sensible about your naming convention so that your name won't conflict with anything else, you're generally ok.