在页面加载时运行脚本

时间:2013-04-16 16:21:45

标签: javascript jquery

我正在使用CMS系统,并限制我可以放置代码的位置(目前)。我正在尝试使用的脚本必须在表单后加载,并且它在Dreamweaver中成功运行。但是现在我要把东西搬进CMS,我必须在标题中而不是在表单之后运行脚本。我试图在页面加载后使用它加载它:

<script>
$(document).ready(function() {
//You should create the validator only after the definition of the HTML form
var frmvalidator  = new Validator("leadform");
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("first_name","req","Please enter your first name.");
frmvalidator.addValidation("first_name","maxlen=40","Max length for first name is 40.");
frmvalidator.addValidation("first_name","alpha","Please enter your first name.");
frmvalidator.addValidation("last_name","req","Please enter your last name.");
frmvalidator.addValidation("last_name","maxlen=40","Max length for last name is 40.");
frmvalidator.addValidation("last_name","alpha","Please enter your last name.");
frmvalidator.addValidation("email","req","Please enter your e-mail address.");
frmvalidator.addValidation("email","email","Please enter your e-mail address.");
frmvalidator.addValidation("state","dontselect=0","Please select your state.");
});
</script>

我必须相信我只是写错了,但我找不到任何可以帮助我这样做的例子。很明显,我是一个noob编码器 - 任何帮助都会受到赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

$(document).ready(function(event){

// insert code here

});

上面的代码将一直等到文档加载(这意味着所有html包括你的表单都加载到页面中),无论它是在html的头部还是在主体中。您只需要确保在使用jQuery时,将脚本标记与代码放在加载jQuery的脚本标记之后。这是一个加载jQuery版本1.9.1的例子:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- make sure your code is added after jQuery -->
<script src='pathtoyourscript/yourScript.js'></script>