简体   繁体   English

我在将事件侦听器设置为按钮 JS 时遇到问题

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

When I tried set eventlistener to my button(condition with "^") I got Uncaught SyntaxError: Unexpected token < error at HTMLButtonElement.. What to do I don't know.当我尝试将 eventlistener 设置为我的按钮(条件为“^”)时,我得到了 Uncaught SyntaxError: Unexpected token < error at HTMLButtonElement .. 我不知道该怎么办。 Thank you in advance)先感谢您)

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

When you put the call to eval , you pass in the full string stored in the array ( "^somefun()" ).当您调用eval ,您将传入存储在数组中的完整字符串 ( "^somefun()" )。 ^somefun() is a syntax error. ^somefun()是一个语法错误。 You need to slice the string to exclude the ^ .您需要对字符串进行切片以排除^

Some other things that may need reworking:其他一些可能需要返工的事情:

  • Don't use == , for javascript, use === , it prevents unexpected behavior.不要使用== ,对于 javascript,使用=== ,它可以防止意外行为。
  • Don't use eval , most of the time, it is a security concern不要使用eval ,大多数时候,这是一个安全问题
  • Don't access the characters of a string like an array.不要像数组一样访问字符串的字符。

As others pointed out in comments, the issue is with the "op" and this line:正如其他人在评论中指出的那样,问题在于“op”和这一行:

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

Changing it to:将其更改为:

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

Will fix the issue.将解决问题。

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

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