几个月前,我意识到我需要每年使用新链接更新侧边栏。现在,我决定创建一个 javascript 文件并将其链接到每个页面,而不是遍历每个页面并插入链接(大约 20 页)。该脚本将创建链接并将其附加到页面。这意味着每次我们需要创建新链接时,我们只需向 javascript 文件添加一次新行,所做的更改就会反射(reflect)在每个页面上。本质上减少了浏览所有页面和添加新链接所浪费的时间。我想知道这是否是一个好的做法,是否会出现我未能预见到的问题?
代码如下:
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");
最佳答案
我能想到一些缺点,前两个假设代码在 DOM 准备好时运行:
- 可以有重新排列的效果,用户首先看到的是页面 没有侧边栏,然后有它
- 您需要确保 仅运行需要侧边栏的页面上运行的其他代码 创建侧边栏后。
- (@Sheikh Heera)某些搜索引擎将无法索引您的整个页面
传统的处理方式是使用服务器端包含,所以如果可以的话请研究一下。
关于javascript - 使用 Javascript 创建侧边栏是一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744299/