【问题标题】:Switch .js file in multiple html pages在多个html页面中切换.js文件
【发布时间】:2016-06-29 10:35:18
【问题描述】:

我有多个 html 页面,如 dashboard.html, page1.html, page2.html, page3.html 等...和两个 .js 文件,即 example1.jsexample2.js 文件

**

从下面的示例 (dashboard.html) 文件中,如果我单击加载文件 1 链接、此页面和其他 html 页面(page1.html、page2.html 等...) 应该将default.js 文件全部替换为example1.js 文件 剩余的 html 页面,直到我回到仪表板页面并更改为 其他。

**

我可以使用外部库

请检查下面的示例代码是否相同...

PS:我是脚本新手,请帮帮我

dashboard.html

<html>
<head>
    <title>Switch js file</title>
    <script src="jquery.min.js"></script>
    <script src="default.js"></script>
</head>
<body>

    <a href="javascript:;" id="loadExample1">Load File 1</a> | <a href="javascript:;" id="loadExample2">Load File 2</a>

    <h1>Default js file loaded successfully!</h1>

    <a href="Page1.html">Go to Page 1</a>

    <a href="Page2.html">Go to Page 2</a>

</body>
</html>

page1.html、page2.html...

<!DOCTYPE HTML>
<html>
<head>
    <title>Switch js file</title>
    <script src="jquery.min.js"></script>
    <script src="default.js"></script>
</head>
<body>
    <h1>Default js file loaded successfully!</h1>
</body>
</html>

example1.js

$('h1').html('Example1.js file loaded successfully!');

example2.js

$('h1').html('Example2.js file loaded successfully!');

【问题讨论】:

  • 这样的配置通常在服务器端进行,因为一个文档中的客户端 js 不能影响另一个文档(读取不同的 html 文件)。你有办法。您可以使用 cookie developer.mozilla.org/ru/docs/Web/API/Document/cookie 来存储有关在用户浏览器中加载什么脚本的信息。然后您可以添加一个脚本来检查此 cookie 并在页面加载后加载所需的脚本。

标签: javascript jquery html


【解决方案1】:

您可以使用 Jquery 的 getScript 函数,将所需的 javascript 文件异步检索到您的页面:

$("someButton").click(function(){
  $.getScript("someScriptFile.js");
}); 

【讨论】:

  • 我不知道该说什么。但是是的,您可以使用 Jquery 的 getScript 函数,将所需的 javascript 文件异步检索到您的页面
猜你喜欢
  • 2022-01-10
  • 2016-01-03
  • 2012-08-22
  • 2017-06-15
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多