簡體   English   中英

嘗試通過 JavaScript 中的按鈕傳遞 function 時未捕獲的參考錯誤?

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

我正在嘗試在我的 web 應用程序的頂部編寫一個導航欄來更改后端的參數,但是當我調用 function 它總是返回一個意外的輸入結束或一個未捕獲的參考錯誤,說明我的 ZC1C425268E618395D 上未定義點擊。 有人可以幫我弄清楚我做錯了什么嗎?

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 文件(包括程序的 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>

看起來您在構建 str 時遇到了一些錯誤。 嘗試這個

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

正確使用模板文字(模板字符串)

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>

正確使用模板文字(模板字符串)

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

只是為了理解目的:
這里的問題是 html 屬性值必須用單引號或雙引號括起來。 使用您的代碼,環繞按鈕的 onlick 屬性值的引號不在您想要的位置,因為您以雙引號開頭,但也用雙引號將 function 包裹起來,因此末尾的元素如下所示:
<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>

要解決此問題,請使用雙引號和單引號:

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

或使用模板文字(其他答案已經提到):

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

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

修改后的代碼片段

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM