简体   繁体   中英

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. Can someone please help me figure out what I'm doing wrong?

JS File:

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>
  <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. 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. 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:
<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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM