0

几个月前,我意识到我需要每年用一个新链接更新一个侧边栏。现在,我决定创建一个 javascript 文件并将其链接到每个页面,而不是浏览每个页面并插入链接(大约 20 页)。该脚本将创建链接并将它们附加到页面。这意味着每次我们需要创建一个新链接时,我们只需要在 javascript 文件中添加一个新行,更改就会反映在每个页面上。基本上减少了浏览所有页面和添加新链接所浪费的时间。我想知道这是否是一个好的做法,会不会有我没有预见到的问题?

代码如下:

function createVolume (text, link){
  var volDiv = document.createElement("div");
  var textDiv = document.createTextNode(text);
  var linkDiv = document.createElement("a");
  linkDiv.setAttribute("href", link);
  volDiv.setAttribute("class", "volume");
  volDiv.appendChild(textDiv);
  linkDiv.appendChild(volDiv);
  var d = document.getElementById("e27");
  d.appendChild(linkDiv);
}
var bhbHome = createVolume("BHB Home", "bhb.html");
var v76 = createVolume("Volume 76", "bhb76.html");
var v75 = createVolume("Volume 75", "bhb75.html");
var v74 = createVolume("Volume 74", "bhb74.html");
var v73 = createVolume("Volume 73", "bhb73.html");
var v72 = createVolume("Volume 72", "bhb72.html");
var v71 = createVolume("Volume 71", "bhb71.html");
var v70 = createVolume("Volume 70", "bhb70.html");
var v69 = createVolume("Volume 69", "bhb69.html");
var v68 = createVolume("Volume 68", "bhb68.html");
var v67 = createVolume("Volume 67", "bhb67.html");
var v6566 = createVolume("Volume 65 and 66", "bhb_65_66.html");
var v64 = createVolume("Volume 64", "bhb64.html");
var v63 = createVolume("Volume 63", "bhb63.html");
var v626160 = createVolume("Volume 60, 61, and 62", "bhb_60_61_62.html");
var v59 = createVolume("Volume 59","bhb59.html");
4

5 回答 5

1

这不是一个好习惯。您应该使用服务器端代码来执行此操作,例如服务器端包含、php 等。这样做对于没有 Javscript 的人来说是行不通的,而良好的做法是在服务器端进行。

于 2013-09-11T14:45:24.883 回答
1

不,最直接的解决方案是使用服务器端脚本。

如果您的页面主要是静态的,并且很少更新,那么假设它可以工作。但实际上,只需使用 wordpress 或其他东西。

于 2013-09-11T14:45:47.203 回答
1

我能想到一些缺点,前两个假设代码在 DOM 准备好时运行:

  1. 可以有一个重新排列的效果,用户首先看到没有侧边栏的页面,然后看到它
  2. 您需要确保页面上运行的需要侧边栏的其他代码仅在创建侧边栏后运行。
  3. (@Sheikh Heera)一些搜索引擎将无法索引您的整个页面

传统的做事方式是使用服务器端包含,所以如果可以的话,请研究一下。

于 2013-09-11T14:47:14.473 回答
1

这不是好习惯!!!!!!!!!!

使用参考文献来引用为什么它不是一个好的做法和可能的问题

不要假设用户拥有支持动态 HTTP 内容的服务器

不要假设用户希望搜索引擎获得他们的链接

于 2013-09-11T14:47:18.050 回答
0

出于维护目的,只创建一次重复使用的元素绝对是一个好主意。但是,出于以下原因,我总是更喜欢在服务器端执行此操作:

  1. 包含脚本客户端将导致不必要的 http 请求。
  2. 浏览器需要启用 Javascript。
  3. 这会导致不必要的 DOM 操作。我离成为专家还很遥远,但我相信这将花费一些时间。

这个列表肯定是不完整的,但这些是最困扰我的话题。如果由于某种原因您没有机会或没有使用服务器端编程语言的知识,您可能想深入研究Server Side Includes。这为您想要实现的目标提供了一种非常易于使用的技术,并且应该可以在常见的 Web 服务器上使用。

于 2013-09-11T14:59:04.667 回答