【问题标题】:Passing multiple parameters to function using settAtribute "onclick" in Javascript?在Javascript中使用settAtribute“onclick”传递多个参数以发挥作用?
【发布时间】:2020-09-21 02:16:52
【问题描述】:

在我的代码中我需要这样做:

function myFunction() {
        /*more code*/
        let id = 12;
        let name = "something";
        deleteBtn.setAttribute("onclick", "otherFunction("+id+","+name+")");
}

其中

function otherFunction(id, name){
        /*does other stuf*/
}

问题是,当我运行代码并加载 html 页面时,我收到此错误: SyntaxError: missing ) after argument list.

我不知道我做错了什么。

【问题讨论】:

  • deleteBtn.onclick = () => otherFunction(id, name);
  • deleteBtn.addEventListener('click', () => otherFunction(id, name))
  • 那个代码不会有那种效果。如果您将name 更改为其中带有空格的东西,我可以看到它会产生这种效果。您应该提供minimal reproducible example 并使用问题编辑器的实时演示功能。
  • 以编程方式,通过将字符串混合在一起来生成 JavaScript 是一场噩梦:它很难调试,并且具有任何涉及 eval 类进程的常见安全风险。不要这样做。使用addEventListener 和函数而不是字符串。

标签: javascript html parameter-passing


【解决方案1】:

当涉及到语法错误时,请重新检查您输入的内容

首先我没有看到你声明了 deleteBtn 变量

deleteBtn.setAttribute("onclick", "otherFunction("+id+","+name+")");

检查此代码是否有效

document.getElementById('asd').setAttribute('onclick', `otherFunction("${id}","${name}")`);

【讨论】:

  • 像这样使用它.setAttribute('onclick', `otherFunction("${id}","${name}")`);让它工作
猜你喜欢
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多