【发布时间】:2020-09-09 21:24:35
【问题描述】:
我正在创建一个用于练习 JavaScript 的小东西,但我遇到了一个我无法理解为什么会发生的错误。
浏览器(chrome、firefox)在控制台中给我以下错误消息:“Uncaught TypeError: Cannot read property 'querySelectorAll' of null at script.js:12”,但是当我尝试 JSFiddle 中的代码时,一切都是按预期工作。浏览器中允许使用 JavaScript,因此通常它应该可以正常工作。
按照HTML DOM querySelectorAll() Method正常,浏览器应该能正确显示代码。
另一个问题是:我怎样才能避免输入这么多的 if 呢?如果我想使用 JavaScript 开关,我应该怎么写?
//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/en/";
console.log(findUrl);
if (findUrl.match(/en/)) {
console.log("The match has been found!");
//select the paragraph inside the div with id #texts
let findP = document.getElementById("texts").querySelectorAll("p");
//define a variable with the new text
let newtxtEN = "A very long text in English to replace the lorem ipsum";
//replace the lorem ipsum text
findP[0].innerText = newtxtEN;
}
if(findUrl.match(/fr/)) {
console.log("The match has been found!");
//select the paragraph inside the div with id #texts
let findP = document.getElementById("texts").querySelectorAll("p");
//define a variable with the new text
let newtxtFR = "Je ne parle pas français";
//replace the lorem ipsum text
findP[0].innerText = newtxtFR;
}
if(findUrl.match(/de/)) {
console.log("The match has been found!");
//select the paragraph inside the div with id #texts
let findP = document.getElementById("texts").querySelectorAll("p");
//define a variable with the new text
let newtxtDE = "Ich bin kein Deutscher";
//replace the lorem ipsum text
findP[0].innerText = newtxtDE;
}
#texts {
border: 1px solid black;
margin: 5px;
padding: 5px;
color: blue;
}
p {
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
}
<div id="texts">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
Ut,consequuntur.
</p>
</div>
【问题讨论】:
-
我不能说你为什么会收到这个错误,但我可以说你的方法已经过时了,会损害你的页面性能。如果您只对给定元素中的第一个
p感兴趣,请使用.querySelector("p")而不是getElementsByTagName("p"),然后使用[0]索引结果。 Don't use live node lists. -
请将问题集中在一个主题上。回复:
if声明;你不只是想要一个带有翻译的简单对象,不管它是如何生成的吗? (手动,图书馆,...) -
@ScottMarcus 我是个初学者,但感谢您的提示!
-
接受的答案是其中的一部分,但是:由于这是一个已知字符串,因此不需要使用正则表达式 - 您只需在主机之后获取 URL 的第一部分(例如、
en、de等。这可用于直接在对象中查找它,例如translations[language],而不是遍历数组并进行正则表达式匹配。
标签: javascript if-statement switch-statement google-chrome-devtools