繁体   English   中英

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

[英]DOM throwing error because of Multiple HTML files

我正在尝试使用 javascript 创建一个简单的食谱应用程序。 我有 3 个 HTML 文件:index.html、create.html、edit.ZFC35FDC70D22C69D269ZEZ 和 28 个文件。

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

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

这里的问题是错误的代码是关于edit.html not index.html。 edit.html 上的同样问题

Uncaught TypeError: Cannot read property 'appendChild' of null
at recipe.js:55

recipe.js 代码 55 是关于 index.html,而不是编辑。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 上

我正在使用本地存储。

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

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

Note that if you load index.html by default (as in, http://localhost:80/ as opposed to http://localhost:80/index.html ), then the pathname will simply be / , so make sure you处理这两个,即:

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

更好的方法是对其进行防御性编码。 在对它运行 function 之前检查你得到的元素是否存在。 例如:

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

除了其中任何一个,您还可以在edit.js上加载index.js ,在index.htmledit.html等,尽管您希望将任何共享函数拆分为单独的(通用)JS 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM