【问题标题】:When trying to get innerHTML, result is always undefined尝试获取 innerHTML 时,结果始终未定义
【发布时间】:2022-01-21 16:46:46
【问题描述】:

我正在生成一些 div 并使用此函数附加到 DOM

//Run forEach method on newObj(cats from local storage) to populate and append template to the DOM
    function getTheCats() {
        //Limiting the results to 3.  Probably better way to do this.
        newObj.slice(0, 3).forEach(cat => {
            const catEl = document.createElement('div')
            catEl.classList.add('cat-detail')
            catEl.innerHTML = `
            <div class="img-id-container" id="pointer-control" onclick="getCatDeets()">
            <img class='cat-image' src='${cat.thumbnail_url}' alt="Cat Pic"/>
            <h3 class="id-left">Cat ${cat.id}</h3>
            </div>
            <p class="birthday-left">${cat.birthdate}</p>
            `
            mainLeft.appendChild(catEl)
        })
    }
    getTheCats()

当我单击其中一个结果时,我正在尝试登录到控制台,一些 innerHTML。 结果,我总是得到“未定义”。我知道我错过了一些东西,但我似乎无法弄清楚是什么。任何帮助将不胜感激。


    function myFunction(event) {
        const clickedCat = event.target.nodeName;
        console.log(clickedCat);
        const details = clickedCat.innerHTML
        console.log(details)
      }

【问题讨论】:

  • 试试event.target.innerHTMLclickedCat 不是target,而是.target.nodeName。我认为.nodeName 把你搞砸了。
  • David784,你是对的!谢谢!!!

标签: javascript events undefined innerhtml


【解决方案1】:

来自 cmets 中的 David784,

我不必要地将 .nodeName 添加到 event.target 我用 .innerHTML 替换了它,我能够检索我需要的数据。

function myFunction(event) {
        const clickedCat = event.target.innerHTML;
        console.log(clickedCat);
        const details = clickedCat.innerHTML
        console.log(details)
      }

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 2015-03-23
    • 2022-01-11
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2013-11-18
    • 2013-05-21
    相关资源
    最近更新 更多