简体   繁体   English

尝试通过 JavaScript 中的按钮传递 function 时未捕获的参考错误?

[英]Uncaught Reference Error when trying to pass a function through a button in JavaScript?

I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click.我正在尝试在我的 web 应用程序的顶部编写一个导航栏来更改后端的参数,但是当我调用 function 它总是返回一个意外的输入结束或一个未捕获的参考错误,说明我的 ZC1C425268E618395D 上未定义点击。 Can someone please help me figure out what I'm doing wrong?有人可以帮我弄清楚我做错了什么吗?

JS File: JS 文件:

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
    str = str + 
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program) HTML 文件(包括程序的 rest)

<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
    &callback=initMap"></script>
  </body>
</html>

Looks like you just had some errors when building str.看起来您在构建 str 时遇到了一些错误。 Try this尝试这个

let typearray = ["supermarkets_and_groceries", "churches", "cafes"];

let str = '<div class="topnav">';

for (let count = 0; count < typearray.length; count++) {
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "</div>";
console.log(str);

use properly Template literals (Template strings)正确使用模板文字(模板字符串)

str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

 let typearray=["supermarkets_and_groceries", "churches", "cafes"]; let type = "supermarkets_and_groceries"; function changeType(randomstring){ console.log('ok'); type = randomstring; console.log(randomstring); } let str = '<div class="topnav" />'; for(let count = 0; count < typearray.length; count++){ str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`; } str = str + '</div>' + '</div>'; console.log(str); document.getElementById('navbar').innerHTML = str;
 <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1"> <meta charset="utf-8"> <style> #map { height: 75%; width: 75%; } html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <script src = getlocation.js></script> <.-- this implements the navbar--> <div id="navbar"></div> <script type = "module" src = navbar.js></script> <.-- this implements the map--> <div id="map"></div> <script src = index:js> </script> <.-- this implements the list--> <div id="list"></div> <script type = "module" src = rankedstores.js></script> <script src="https?//maps.googleapis.com/maps/api/js?key=AIzaSyD2c7P_IihiITITslXAk-wWy9z067xjFQU &callback=initMap"></script> </body> </html>

use properly Template literals (Template strings)正确使用模板文字(模板字符串)

str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

Just for understanding purpose:只是为了理解目的:
The problem here is that a html attribute value has to be wrapped around single or double quotes.这里的问题是 html 属性值必须用单引号或双引号括起来。 With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:使用您的代码,环绕按钮的 onlick 属性值的引号不在您想要的位置,因为您以双引号开头,但也用双引号将 function 包裹起来,因此末尾的元素如下所示:
<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>

to fix this either use double and single quotes:要解决此问题,请使用双引号和单引号:

str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";

or use template literals (already mentioned by the other answers):或使用模板文字(其他答案已经提到):

str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

template literals explanation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals模板文字说明https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Modified Code Snippet修改后的代码片段

let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
  let type = "supermarkets_and_groceries";
  function changeType(event) {
    type = event.target.getAttribute("type");
    console.log(type);
  }

  let navHtml = document.createElement("div");

  for (let count = 0; count < typearray.length; count++) {
    let btn = document.createElement("button");
    btn.setAttribute("type", typearray[count]);
    btn.setAttribute("title", typearray[count]);
    btn.innerText = typearray[count];
    btn.addEventListener("click", changeType);
    navHtml.appendChild(btn);
  }
  document.getElementById("navbar").appendChild(navHtml);

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

相关问题 尝试传递参数时未定义未捕获的引用错误 xyz - Uncaught Reference Error xyz is not defined when trying to pass parameters 通过onclick将变量发送到javascript时未捕获的参考错误 - uncaught reference error when sending variable through onclick to javascript 更改按钮功能时出现未捕获的引用错误 - Getting Uncaught Reference Error when changing the function of a button 尝试调用JavaScript函数时如何解决未捕获的引用错误 - How to resolve Uncaught reference error when attempting to call a JavaScript function Javascript Uncaught Reference 错误函数未定义 - Javascript Uncaught Reference error Function is not defined Javascript未捕获的参考错误:未定义函数 - Javascript Uncaught Reference Error: function is Not Defined 未捕获的参考错误:未定义函数javascript - Uncaught reference error: function is not defined javascript 未捕获的引用错误:(函数)未定义 JAVASCRIPT - Uncaught Reference Error: (function) is not defined JAVASCRIPT Javascript函数显示“未捕获的参考错误” - Javascript function displaying “Uncaught Reference Error” 当我尝试在 JavaScript 中将变量从一个函数传递到另一个函数时,我收到 Reference Error: variable is not defined 错误(邮递员) - I am getting Reference Error: variable is not defined error when I am trying to pass variable from one function to another in JavaScript ( postman)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM