如何解决从另一个外部js文件调用外部js函数会产生“未定义”错误
|| 我在plugins.js中有以下代码:$(document).ready(function() {
watermark = function(elemId,text,hoverClass,normalClass,parentId){
// onFocus event
$(\"#\"+elemId).focus(function(){
($(this).val()==text)
$(this).val(\'\');
(parentId!=0)
byId(parentId).className = hoverClass;
});
// onBlur event
$(\"#\"+elemId).blur(function(){
($(this).val()==\'\')
$(this).val(text);
(parentId!=0)
byId(parentId).className = normalClass;
});
}
});
然后我在index.js文件中有这个:
new watermark(\"footer_contact_name\",\"Name\",\"footer_form_text_active\",\"footer_form_text\",\"footer_form_field_1\");
在同一个js文件中编写所有内容时,一切正常,但是当从index.js文件中这样调用它时,我在FireFox中使用Firebug进行调试时出现未定义的函数错误。
有任何想法吗?
谢谢
顺便说一句:我将这些包括在index.html中,如下所示:
<script src=\"scripts/plugins.js\" type=\"text/javascript\"></script>
<script src=\"scripts/index.js\" type=\"text/javascript\"></script>
解决方法
准备好文档后需要调用该函数-将其包装在:
$(document).ready(function() { });
, 当准备好操作DOM时,将声明watermark
函数(在$(document).ready(function()
中,因此there6ѭ被包含时将不可用。
编辑:
在DOM准备好被操纵之后,您就不得不调用watermark
,因为它使用DOM中的元素。一种解决方案是在$(document).ready(function()
之外声明watermark
函数,然后在$(function() {
($(document).ready()
的简写)中从index.js
调用它:
functions.js:
watermark = function(elemId,text,hoverClass,normalClass,parentId){
// function logic
}
index.js:
$(function() {
new watermark(\"footer_contact_name\",\"Name\",\"footer_form_text_active\",\"footer_form_text\",\"footer_form_field_1\");
}
, 您仅在加载DOM后定义watermark()
函数。您可以在$(document).ready()
调用之外定义它,也可以将$(document).ready()
调用嵌入其中,因此它将在加载DOM时执行,但在此之前可用。
例如:
watermark = function(elemId,parentId) {
$(document).ready(function() {
/* ... */
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。