【问题标题】:Selecting a P inside a DIV gives error in browser console but in JsFiddle works fine. Why?在 DIV 中选择 P 会在浏览器控制台中出现错误,但在 JsFiddle 中可以正常工作。为什么?
【发布时间】: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 的第一部分(例如、ende 等。这可用于直接在对象中查找它,例如 translations[language],而不是遍历数组并进行正则表达式匹配。

标签: javascript if-statement switch-statement google-chrome-devtools


【解决方案1】:

您可以使用对象数组来避免所有重复代码。

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/en/";
console.log(findUrl);

const langs = [{
    pattern: /en/,
    text: "A very long text in English to replace the lorem ipsum"
  },
  {
    pattern: /fr/,
    text: "Je ne parle pas français"
  },
  {
    pattern: /de/,
    text: "Ich bin kein Deutscher"
  }
];

let found = false;
for (let i = 0; i < langs.length; i++) {
  if (findUrl.match(langs[i].pattern)) {
    console.log("The match has been found!");
    let findP = document.getElementById("texts").querySelectorAll("p");
    findP[0].innerText = langs[i].text;
    found = true;
    break;
  }
}
if (!found) {
  console.log("The match was not found");
}
#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>

至于您收到该错误的原因,请参阅Why does jQuery or a DOM method such as getElementById not find the element?

【讨论】:

  • 我非常感谢所提供的优雅解决方案以及用于解释错误出现在浏览器中的原因的链接。我将脚本向下移动到&lt;/body&gt; 附近,错误消失了。谢谢!
【解决方案2】:

我们无法在此处重现您的问题,并且代码可以按您的意愿运行,因此我们可能无法为您提供简明的答案。

但是,您的代码非常过时,并且因为您使用的是.getElementsByTagName(),所以您使用的是“实时”节点列表,这可能会损害您的页面和really shouldn't be used 的性能。此外,由于您只对节点列表中找到的第一个元素感兴趣,因此收集所有匹配项只是将除第一个之外的所有匹配项都扔掉也是一种浪费。

最后,你有一堆不需要的重复代码。请参阅下面的代码以获得更合适的解决方案。

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/en/";
console.log(findUrl);

let matchFound = "not ";

// You only need to do this once, not in each of your if statements
// since the result isn't going to change. And use .querySelector(),
// not .getElementsByTagName().
let findP = document.getElementById("texts").querySelector("p");

// Instead of 3 separate if statements, use else if so that once you
// have a true condition, the other statemens won't be processed.
if (findUrl.match(/en/)) {
  findP.textContent = "A very long text in English to replace the lorem ipsum";
  matchFound = "";
} else if(findUrl.match(/fr/)) {
  findP.textContent = "Je ne parle pas français";
  matchFound = "";
} else if(findUrl.match(/de/)) {
  findP.textContent = "Ich bi)n kein Deutscher";
  matchFound = "";
}

console.log("The match was " + matchFound + "found."); 
#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>

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2018-12-11
    • 2018-07-26
    • 1970-01-01
    相关资源
    最近更新 更多