我用脚本创建了一个按钮.我可以通过点击按钮调用其他函数吗?我这样做,但失败了

I create a button by script. Can I call other function by clicking the button? I do it like this, but fail

本文关键字:按钮 函数 其他 调用 失败 这样做 可以通过 创建 脚本 一个      更新时间:2024-05-24

我在这个脚本中添加了一个按钮。我可以用这个按钮调用其他功能吗。如下所示:newinput.onclick="check();";我试过了,但没有回应。

  inform = document.getElementById('addinput');
  newinput = document.createElement('input');
  newinput.type = "text";
  newinput.name = "NumA" + i;
  newinput.id = "NumA" + i;
  newinput.value = a;
  inform.appendChild(newinput);

  newinput = document.createElement('input');
  newinput.type = "button";
  newinput.name = "submit";
  newinput.value = "Check";
  **newinput.onclick = "check();";**
  inform.appendChild(newinput);
  }

  function check() {
  window.alert("It is test!");
  }

您必须编写不带括号的函数名:

newinput.onclick = check;

看看它是如何在JsFiddle上工作的。

说明:通过将函数名称放在Paradishesion中,您可以在该位置调用函数。onclick实际上将被分配该函数的返回值。另一方面,只传递对象(在本例中为函数)的名称,就可以将引用分配给该对象(函数)。

尝试类似的东西

newinput.setAttribute('onClick','yourFunction();');

尽管你可能需要放弃分号,但我不能百分之百确定。

newinput.setAttribute('onClick','yourFunction()');