将Javascript从html移到外部文件
Moving Javascript from the html to an external file
我在使用一些javascript时遇到了麻烦,我试图从内联转换为外部javascript文档。这段代码,我试图放在外部不起作用。
// 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);
}
});
}
试图锁定脚本,因此:
$(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);
}
});}
});
我认为它"不起作用"是因为你的jQuery选择器失败了。把你的代码放在里面作为$(function () {...})
,以确保它可以在dom上运行。
您的代码让我认为您正在使用jQuery。要将使用jQuery等库的JS文件移动到外部文件,必须执行以下步骤:
如果代码在jQuery内部,看起来像这样:
$(document).ready(function(){
// here is all your code
});
然后你必须移动所有的,包括$(document).ready();
部分到外部文件和(最好)加载它在你的html页面的底部。
相关文章:
- 将外部文件与AngularJs集成
- 动态地包含来自外部文件PHP的JavaScript
- LeadLander formalyze_init.js Javascript外部文件
- 我的代码在<脚本>标记,但没有'不能在外部文件中工作
- 如何用HTML中的JSON外部文件填充下拉按钮
- 如何在从外部连接时将外部文件包含到node-js项目中
- 访问模块.从外部文件导出
- 无法从 jquery 中的外部文件调用特定内容
- 无法让 javascript 从外部文件工作
- 将变量从服务器上的外部文件加载到 HTML 文档中
- 对 jquery 库 + 外部文件的 HTML 引用
- 如何在 webpack 中包含外部文件
- Highcharts赢得't加载表单外部文件
- 如何在外部文件中创建选择菜单并将其嵌入到html中以显示菜单
- Javascript和CSS,内部HTML与外部文件
- 包括从外部文件到HTML的查询功能(使用Dropbox进行本地测试)
- 使用load()加载外部文件,然后使用fancybox插件进行修改并显示
- 如何在外部文件中存储谷歌地图选项
- 用javascript(不带外部文件)将html加载到另一个html中
- 从外部文件设置tinymce的内容