【问题标题】:Uncaught TypeError: Cannot assign to read only property 'tagName' of object '#<HTMLImageElement>'未捕获的类型错误:无法分配给对象“#<HTMLImageElement>”的只读属性“tagName”
【发布时间】:2020-08-20 19:22:42
【问题描述】:

每当我在浏览器中单击 &lt;li&gt; 元素内的空闲空间时,我都会收到一个显示标题 (gridMainTitle) 的窗口警报。这没关系。但是在这个&lt;li&gt; 元素上,我设置了一个小网格布局,对齐图像和一些文本。我现在的问题是,如果我单击网格内和 li 元素上的那个图像对象,我还想发出警报。但我只收到一条错误消息:Uncaught TypeError: Cannot assign to read only property 'tagName' of object '#&lt;HTMLImageElement&gt;'

this.listRoot = this.mainView.querySelector("ul");
this.listRoot.onclick = (evt) => {
  const selectedLi = this.find(evt.target);
  
  if (selectedLi) {
    alert("clicked on: " + this.getTitleFromLi(selectedLi));
  }
  else {
    alert("something went completely wrong...");
  }
 }
}

find(el) {
  if (el.tagName == "LI") {
    return el;
  }
  else if (el.tagName = "...") { // DIV or IMG doesn't really work.
    return el;
  }
  else if (el.tagName = "UL") {
    return null;
  }
  else if (el.parentNode) {
    return this.find(el.parentNode);
  }
  else { return null; }
}

getTitleFromLi(liElement) {
  return liElement
        .getElementsByClassName("gridMainTitle") [0]
        .textContent;
}
<main class="tiles">
  <ul>
    <li class="grid-container">
      <div class="gridImageObject">
        <img src="imagefile" class="align-left"/>
      </div>
      <div class="gridMainTitle">
        <p class="align-left">Some Text</p>
      </div>
    </li>
  </ul>
</main>

【问题讨论】:

  • 你不见了,= 签名 if (el.tagName = "...")if (el.tagName = "UL") 是分配。你需要 == 或 ===

标签: javascript html typeerror


【解决方案1】:

您使用了单等号(赋值)而不是双等号(比较)。例如

if (el.tagName = "...")

应该是

if (el.tagName == "...")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2020-11-26
    • 2018-06-15
    相关资源
    最近更新 更多