[英]innerHTML in Javascript causing error in multiple HTML files
I have 2 HTML pages which I linked to 1 javascript file.我有 2 个 HTML 页面链接到 1 个 javascript 文件。
In the javascript file, I use innerHTML to get a value from HTML file 1, but the issue is that an error pops up in HTML page 2 as it cannot find the same value.在 javascript 文件中,我使用 innerHTML 从 HTML 文件 1 中获取值,但问题是 HTML 第 2 页中弹出错误,因为它找不到相同的值。 Is there a way for me to only check HTML page 1 for the value instead of both pages?有没有办法让我只检查 HTML 第 1 页的值而不是两个页面?
HTML page 1 HTML 第 1 页
<div id = "html1"> Value </div>
<script src = script.js></script>
HTML page 2 HTML 第 2 页
<div id = "html2"> Another Value </div>
<script src = script.js></script>
Javascript Javascript
x = document.getElementById("html1").innerHTML
You would have to add conditions for performing actions.您必须添加执行操作的条件。 something like就像是
if (document.getElementById('html1')) // will return null if doesn't exist.
x = document.getElementById("html1").innerHTML;
But consider separating script files if pages aren't related.但如果页面不相关,请考虑分离脚本文件。
Another option另外的选择
// Shortcut const s = t => document.getElementById(t); // Inline false check: // variable = (if condition true)? then this value: or this value if condition false const x = s("html1")? s("html1").innerHTML: false; const y = s("html2")? s("html2").innerHTML: false; console.log(x, y);
<div id = "html1">Value</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.