由于多个HTML文件,DOM抛出错误

问题描述 投票:0回答:1

我正在尝试使用javascript创建一个简单的食谱应用。我有3个HTML文件:index.html,create.html,edit.html和2个JS文件。

我有几个DOM元素。一个在index.html上,两个在编辑上,两个在创建上。现在,当我打开index.html时,出现错误:

recipe.js:14 Uncaught TypeError: Cannot set property 'value' of null

这里的问题是错误的代码是关于edit.html而不是index.html。edit.html

上的同样问题
Uncaught TypeError: Cannot read property 'appendChild' of null
at recipe.js:55

recipe.js代码55与index.html有关,而不是edit.html。

使用DOM时,有没有一种方法可以将HTML文件定位为目标。

document.getElementById("edit-body").value = getRecipeBody();

我希望上面的代码仅用于edit.html,而不用于index.html或create.html。

edit-body是仅在edit.html上,而不在index或create.html上的表单

document.getElementById('recipes').appendChild(recipeEl)

我希望此代码用于index.html,而不用于其他HTML文件,因为这些文件上没有#recipes ID。 #recipes仅在index.html

我正在使用localStorage。

javascript html dom getelementbyid
1个回答
0
投票

window.location.pathname将让您执行特定路径的代码。

if(window.location.pathname === '/edit.html') {
  document.getElementById("edit-body").value = getRecipeBody();
}

请注意,如果您默认加载index.html(如http://localhost:80/而不是http://localhost:80/index.html),那么路径名将只是/,因此请确保您同时处理了这两个名称,即:

if(window.location.pathname === '/index.html' || window.location.pathname === '/') {
  document.getElementById('recipes').appendChild(recipeEl)
}

更好的方法是对它进行防御性编码。在对它运行功能之前,请检查要获取的元素是否存在。例如:

var editEl = document.getElementById("edit-body");
if (editEl) {
  editEl.value = getRecipeBody();
}

代替这两个方法中的任何一个,您也可以只将index.js加载到index.html,将edit.js加载到edit.html,依此类推,尽管您希望将所有共享功能分解为单独的(通用)JS文件。

© www.soinside.com 2019 - 2024. All rights reserved.