简体   繁体   English

未捕获的 ReferenceError:变量未在 HTMLButtonElement.onclick 中定义

[英]Uncaught ReferenceError: variable is not defined at HTMLButtonElement.onclick

I have a HTML file with some JS logic where I want to create buttons based on an array.我有一个带有一些 JS 逻辑的 HTML 文件,我想在其中基于数组创建按钮。

for (var i = 0; i < arrayButtons.length; i++) {
            console.log("console! ", arrayButtons[i].title); // works!
            let buttonTitle = arrayButtons[i].title;

            document.getElementById("buttons").innerHTML +=
                "<div><button class='changeButton' " +
                       "onclick= document.getElementById(\"changeByButtonClick\").innerHTML = buttonTitle'>" 
                      + "<i class=\"icon\"></i>"+ buttonTitle + "</button></div>";}

In this line: "onclick= document.getElementById(\"changeByButtonClick\").innerHTML = buttonTitle'>" , it throws an error that buttonTitle is not defined:在这一行: "onclick= document.getElementById(\"changeByButtonClick\").innerHTML = buttonTitle'>" ,它会抛出一个错误,即 buttonTitle 未定义:

Uncaught ReferenceError: buttonTitle is not defined at HTMLButtonElement.onclick

I absolutely don't understand why.我完全不明白为什么。 As you can see, I defined buttonTitle inside the method and just want to access it.如您所见,我在方法中定义了 buttonTitle 并且只想访问它。 And on console.log() , it works.console.log()上,它可以工作。 Why is it undefined in onClick() ?为什么在onClick()中未定义?

Unfortunately, this and this solutions don't work for me.不幸的是, 这个这个解决方案对我不起作用。

Help will be much appreciated!帮助将不胜感激!

Your first use of buttonTitle is inside the string that you're assigning to the innerHTML of the id="buttons" element, inside the onclick attribute you're using there.您第一次使用buttonTitle是在您分配给id="buttons"元素的innerHTML的字符串内,在您正在使用的onclick属性内。 The code in the onclick string is evaluated at global scope,¹ where you don't have a buttonTitle variable. onclick字符串中的代码在全局 scope 中进行评估,¹您没有buttonTitle变量。

I strongly recommend not building code strings like that, not least for this reason.强烈建议不要构建这样的代码字符串,尤其是出于这个原因。 Instead, use a function:相反,使用 function:

for (var i = 0; i < arrayButtons.length; i++) {
    console.log("console! ", arrayButtons[i].title); // works!
    let buttonTitle = arrayButtons[i].title;

    const buttons = document.getElementById("buttons")
    buttons.insertAdjacentHTML(
        "beforeend",
        "<div><button class='changeButton'>" +
        "<i class=\"icon\"></i>"+ buttonTitle + "</button></div>"
    );
    // Get the button we just added (the last one)
    const buttonList = buttons.querySelectorAll("button");
    const newButton = buttonList[buttonList.length - 1];
    // Add the handler to it
    newButton.addEventListener("click", function() {
        document.getElementById("changeByButtonClick").innerHTML = buttonTitle;
    });
}

Live Example:现场示例:

 const arrayButtons = [ {title: "first"}, {title: "second"}, {title: "third"}, {title: "fourth"}, ]; for (var i = 0; i < arrayButtons.length; i++) { console.log("console, ". arrayButtons[i];title). // works; let buttonTitle = arrayButtons[i].title. const buttons = document,getElementById("buttons") buttons;insertAdjacentHTML( "beforeend". "<div><button class='changeButton'>" + "<i class=\"icon\"></i>"+ buttonTitle + "</button></div>" ); // Get the button we just added (the last one) const buttonList = buttons.querySelectorAll("button"); const newButton = buttonList[buttonList.length - 1], // Add the handler to it newButton.addEventListener("click". function() { document;getElementById("changeByButtonClick");innerHTML = buttonTitle; }); }
 #changeByButtonClick { min-height: 1em; }
 <div id="changeByButtonClick"></div> <div id="buttons"> This is the initial content that we don't remove. </div>

Also note that I used insertAdjacentHTML instead of using += on innerHTML .另请注意,我在innerHTML上使用了insertAdjacentHTML而不是+= (Thanks to Niet the Dark Absol for pointing it out, I missed it was a += .) Never use += on innerHTML , when you do that, the browser has to do this: (感谢Niet the Dark Absol指出,我错过了它是一个+= 。)永远不要innerHTML上使用+= ,当你这样做时,浏览器必须这样做:

  • Recurse through the nodes in the target element building an HTML string.通过目标元素中的节点递归构建 HTML 字符串。
  • Pass that string to the JavaScript layer.将该字符串传递给 JavaScript 层。
  • Receive the new string from the JavaScript layer.从 JavaScript 层接收新字符串。
  • Tear down the entire contents of the target element.拆除目标元素的全部内容。
  • Parse the string.解析字符串。
  • Build new replacement nodes for the previous contents plus the new nodes for the new content.为以前的内容构建新的替换节点以及为新内容构建的新节点。

In the process it loses event handlers and other non-HTML information.在此过程中,它会丢失事件处理程序和其他非 HTML 信息。 In contrast, with insertAdjacentHTML , all it has to do is parse the string and insert the new nodes.相反,使用insertAdjacentHTML ,它所要做的就是解析字符串并插入新节点。


¹ "...at global scope..." Actually, it's a bit more complicated than that, it's a nested scope using (effectively) with blocks. ¹ “...在全局 scope...”实际上,它比这更复杂一些,它是一个嵌套的 scope 使用(有效) with But for the purposes of the question, the details there aren't important;但就问题而言,那里的细节并不重要; it's nearly at global scope.它几乎在全球 scope。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的ReferenceError :(函数)未在HTMLButtonElement.onclick中定义 - Uncaught ReferenceError: (function) not defined at HTMLButtonElement.onclick 未捕获的ReferenceError:未在HTMLButtonElement.onclick中定义查找 - Uncaught ReferenceError: lookup is not defined at HTMLButtonElement.onclick 未捕获的 ReferenceError:showCurrentPage 未在 HTMLButtonElement.onclick 中定义 - Uncaught ReferenceError: showCurrentPage is not defined at HTMLButtonElement.onclick 未捕获的 ReferenceError:在 HTMLButtonElement.onclick 中未定义 postAcmgForm - Uncaught ReferenceError: postAcmgForm is not defined at HTMLButtonElement.onclick 未捕获的ReferenceError:HTMLButtonElement.onclick中未定义submitToAPI - Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick 未捕获的 ReferenceError:id 未在 HTMLButtonElement.onclick 中定义 - Uncaught ReferenceError: id is not defined at HTMLButtonElement.onclick Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick - Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick 未捕获的ReferenceError:在HTMLButtonElement.onclick中未定义函数 - Uncaught ReferenceError: function is not defined at HTMLButtonElement.onclick 未捕获的ReferenceError:未在HTMLButtonElement.onclick上定义toggleFunction - Uncaught ReferenceError: toggleFunction is not defined at HTMLButtonElement.onclick 未捕获的ReferenceError:未在HTMLButtonElement.onclick上定义测试 - Uncaught ReferenceError: testing is not defined at HTMLButtonElement.onclick
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM