多个jQuery .ready()-附加到现有事件处理程序,而不是创建另一个事件处理程序 [英] Multiple jQuery .ready() - appending to existing event handler instead of creating another one

查看:87
本文介绍了多个jQuery .ready()-附加到现有事件处理程序,而不是创建另一个事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

...
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript" src="[pagename]_specific.js"></script>
...

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

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

general.js:

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

home_specific.js :"[pagename] _specific.js"的示例

home_specific.js: an example of "[pagename]_specific.js"

jQuery(function() {
  foo = function() {alert("hello")};
}

其中#btn是按钮元素.

"general.js"是一个由多个页面共享的脚本,而每个页面都有其专用的"[pagename] _specific.js",用于定义分配给foo的功能的行为.

"general.js" is a script that is shared by multiple pages, while each page has its dedicated "[pagename]_specific.js" for defining how the function assigned to foo behaves.

当我单击#btn时,我希望看到"hello"对话框,但是,我在chrome开发人员工具中看到了Uncaught TypeError: undefined is not a function.来自此问题,我理解这是因为两个.ready()具有两个单独的事件处理程序.

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. From this SO question, I understand that's because the two .ready() have two separate event handlers.

问题:"[pagename] _specific.js"中的.ready()是否可以附加到"general.js"中的.ready()的事件处理程序中?另一个匿名功能?

Question: Is there any way that the .ready() in "[pagename]_specific.js" appends to the event handler of the .ready() in "general.js", instead of defining another anonymous function?

推荐答案

脚本中实际发生的事情与您所想的不同.

What is actually happening in your scripts is different than what you think.

以下:

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

您已经通过在foo前面键入var创建了foo的本地副本. 在这种情况下,foo是未定义的.

you have created a local copy of foo by typing var in front of it. In this case foo is undefined.

以下:

jQuery(function() {
  foo = function() {alert("hello")};
}

您实际上已经制作了称为foo的全局可访问函数.但这直到被调用才执行. 但是在第一个脚本中,您尝试调用它.但是实际上发生的是您的脚本尝试使用它自己的本地定义的变量foo,该变量未定义.

You have actually made globally accesible function called foo. But this will not execute until called. But in the first script, you try calling it. But what actually happens is your script try's using its own locally defined variable called foo, which is undefined.

以下是我会做的

// general.js:
jQuery(function() {
  $('#btn').click(function() { 
    foo(); 
  });
});

// home_specific.js
var foo = function() {
  alert("hello");
};

我希望这对您有所帮助!希望您了解发生了什么事!

Well I hope this has helped!! Hope you understand what's going on!

这篇关于多个jQuery .ready()-附加到现有事件处理程序,而不是创建另一个事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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