在多个脚本中定义的jQuery .ready()中使用相同的变量 [英] Working with the same variable across the jQuery .ready() defined in multiple scripts

查看:66
本文介绍了在多个脚本中定义的jQuery .ready()中使用相同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个链接到两个脚本的HTML:

...
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript" src="specific.js"></script>
...

两个脚本中的每个脚本都有自己定义的jQuery .ready().

general.js:

jQuery(function() {
  var foo;
  $('#btn').click(function() {alert(foo())});
}

specific.js:

jQuery(function() {
  foo = function() {alert("hello")};
  $('#btn').click(function() {foo()});
}

其中#btn是按钮元素.

当我单击#btn时,我希望看到你好"对话框,但是,我在chrome开发人员工具中看到了Uncaught TypeError: undefined is not a function.

我自己的理解是,在通过click事件访问它之前,应该已经为foo分配了该函数,而不是未定义函数.显然,我的理解是不正确的.有人可以向我解释为什么它的行为方式如此吗?

解决方案

您要在第一个函数var 内部中声明"foo".因此,它在该功能本地,在其外部不可见.

您可以通过在第一个就绪"处理程序的外部中声明"foo"来使其全局.

全局变量是不可取的.最好将该值保留为元素本身上的数据"值.

$(function() {
   $('#btn').data('foo', 'some value');
   $('#btn').click(function() {alert($(this).data('foo'))});
}

通过这种方式,数据与元素相关联(尽管不是直接在DOM对象上; jQuery跟踪内部映射中的值以避免DOM相关的内存泄漏),并且您不会污染全局名称空间. /p>

Say that I have a HTML that links to two scripts:

...
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript" src="specific.js"></script>
...

Each of the two scripts has it's own jQuery's .ready() defined.

general.js:

jQuery(function() {
  var foo;
  $('#btn').click(function() {alert(foo())});
}

specific.js:

jQuery(function() {
  foo = function() {alert("hello")};
  $('#btn').click(function() {foo()});
}

where #btn is a button element.

When I clicked on #btn I was expecting to see "hello" dialog, but instead, I got Uncaught TypeError: undefined is not a function in chrome developer tools.

My own understanding is that foo should have been assigned the function already, instead of being undefined, before it's accessed by the click event. Obviously, my understanding is incorrect. Can someone please explain to me why it's behaving the way it is?

解决方案

You're declaring "foo" with var inside the first function. It's therefore local to that function and not visible external to it.

You could make "foo" global by declaring it outside the first "ready" handler.

Global variables are kind-of undesirable; it might be nicer to keep the value as a "data" value on the element itself.

$(function() {
   $('#btn').data('foo', 'some value');
   $('#btn').click(function() {alert($(this).data('foo'))});
}

That way the data is associated with the elements (though not directly on the DOM objects; jQuery keeps track of the values in an internal map to avoid DOM-related memory leaks) and you don't pollute the global namespace.

这篇关于在多个脚本中定义的jQuery .ready()中使用相同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆