簡體   English   中英

我在將事件偵聽器設置為按鈕 JS 時遇到問題

[英]I got a problem with setting eventlistener to button JS

當我嘗試將 eventlistener 設置為我的按鈕(條件為“^”)時,我得到了 Uncaught SyntaxError: Unexpected token < error at HTMLButtonElement .. 我不知道該怎么辦。 先感謝您)

 op = ["button","#hello","^somefun()","<father"]; var el = document.createElement(op[0]); if(op[s][0] == "#"){ el.id = op[s].substring(1,op[s].length); s++; console.log(s); } // set class of element if(op[s][0] == "."){ el.className = op[s].substring(1,op[s].length); s++; console.log(s,el.style.className); } //set text that will be in element if(op[s][0] == "_"){ el.innerHTML = op[s].substring(1,op[s].length); s++ console.log(s); } //there i got a error! if(op[s][0] == "^"){ s++; el.addEventListener("click",function () { eval(op[s]); }); s++; console.log(s); }

當您調用eval ,您將傳入存儲在數組中的完整字符串 ( "^somefun()" )。 ^somefun()是一個語法錯誤。 您需要對字符串進行切片以排除^

其他一些可能需要返工的事情:

  • 不要使用== ,對於 javascript,使用=== ,它可以防止意外行為。
  • 不要使用eval ,大多數時候,這是一個安全問題
  • 不要像數組一樣訪問字符串的字符。

正如其他人在評論中指出的那樣,問題在於“op”和這一行:

op = ["button","#hello","^somefun()","<father"];

將其更改為:

op = ["button","#hello","^somefun()","<father>"];

將解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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