[英]Moving Javascript from the html to an external file
I am having trouble using some javascript that I am trying to convert from inline to an external javascript document. 我在尝试将某些JavaScript从内联转换为外部JavaScript文档时遇到麻烦。 This code, that I'm trying to place externally does not work. 我试图放在外部的此代码不起作用。
// JavaScript Document
function homepage() {
$("#button").click(function(){
$("#main, #nav").slideToggle();
if($(this).html() == "-"){
$(this).html("+");
setTimeout(function() {
$('#wrapper').css('top', 'auto');
$('#wrapper').animate({ 'bottom': '0' }, 500);
}, 500);
} else {
$(this).html("-");
setTimeout(function() {
$('#wrapper').animate({ 'top': '0' }, 500);
$('#wrapper').css('bottom', 'auto');
}, 500);
}
});
}
Tries to lock up the script so: 尝试锁定脚本,以便:
$(document).ready(function(){
// JavaScript Document
function homepage() {
$("#button").click(function(){
$("#main, #nav").slideToggle();
if($(this).html() == "-"){
$(this).html("+");
setTimeout(function() {
$('#wrapper').css('top', 'auto');
$('#wrapper').animate({ 'bottom': '0' }, 500);
}, 500);
}
else{
$(this).html("-");
setTimeout(function() {
$('#wrapper').animate({ 'top': '0' }, 500);
$('#wrapper').css('bottom', 'auto');
}, 500);
}
});}
});
I assume that it "doesn't work" because your jQuery selectors are failing. 我认为它“不起作用”,因为您的jQuery选择器失败了。 Put your code inside as $(function () {...})
to insure it runs on DOM-ready. 将您的代码放入$(function () {...})
以确保其可在DOM就绪的环境下运行。
Your code makes me assume that you are using jQuery. 您的代码使我假设您正在使用jQuery。 To move a JS file that uses a library like jQuery to an external file, you have to do the following steps: 要将使用jQuery之类的库的JS文件移动到外部文件,您必须执行以下步骤:
If the code is inside jQuery and looks like this: 如果代码在jQuery内部,并且看起来像这样:
$(document).ready(function(){
// here is all your code
});
Then you have to move all of it, including the $(document).ready();
然后,您必须移动所有内容,包括$(document).ready();
part into the external file and (best) load it at the bottom of your html page. 部分放入外部文件,并(最好)将其加载到html页面的底部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.