我在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>发布于 2011-06-25 20:15:37
您需要在文档准备就绪后调用该函数-将其包装在:
$(document).ready(function() { });发布于 2011-06-25 20:13:36
watermark函数在DOM准备好操作时声明(在$(document).ready(function()中,因此在包含index.js时将不可用)。
编辑:
您必须在准备好操作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");
}发布于 2011-06-25 20:13:42
您只需在加载DOM之后定义watermark()函数。您可以在$(document).ready()调用外部定义它,也可以将$(document).ready()调用嵌入其中,这样它将在加载DOM时执行,但在此之前可用。
例如:
watermark = function(elemId, text, hoverClass, normalClass, parentId) {
$(document).ready(function() {
/* ... */
}
}https://stackoverflow.com/questions/6477630
复制相似问题