简体   繁体   English

动态添加的功能无法正常运行JavaScript

[英]Dynamically added function is not working correctly JavaScript

I'm trying to create a table made out of user inputs, with those inputs including checkboxes. 我正在尝试创建一个由用户输入组成的表,这些输入包括复选框。 I have a function for what to do when the box is clicked 我有一个功能,单击该框时该怎么办

function checkTheBox(t)  {           
  var t;
    if (array[t] == 0) {
      array[t] = 1;
    }
    else {
      array[t] = 0;
    }
}

and to add that function to the created elements of the table I use 并将该功能添加到我使用的表的已创建元素中

function add() {
  var word = document.getElementById("text").value;
  var tdt = document.createElement("td");
  var tdc = document.createElement("td")
  var node = document.createTextNode(word);
  var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = "cb";
    tdc.addEventListener("click", ticker(0), false);
    tdc.stopPropagation;
  tdt.appendChild(node);
  tdc.appendChild(checkbox);
  var tr = document.createElement("tr");
  tr.appendChild(tdt);
  tr.appendChild(tdc);
  var table = document.getElementById("vt");
  table.appendChild(tr);
}

The problem is that whenever I click on the Add button to create the new element it activates the function and then creates the element and the checkbox does nothing when I click on it. 问题是,每当我单击“添加”按钮以创建新元素时,它都会激活该功能,然后创建该元素,并且当我单击它时,复选框不执行任何操作。

I use the checkTheBox function in the first place because the only other way I've read of dealing with checkboxes is with PHP, which I have yet to delve into. 我首先使用checkTheBox函数,因为我读过的其他处理复选框的方法是使用PHP,而我尚未深入研究。

You're executing ticker(0) immediately, rather than telling it to execute when tdc is clicked. 您正在立即执行ticker(0) ,而不是告诉它在单击tdc时执行。

Here... 这里...

tdc.addEventListener("click", ticker(0), false);

That will assign the result of executing ticker(0) to the click event handler. 这会将执行ticker(0)的结果分配给click事件处理程序。 You can wrap it in an anonymous function so that it is only executed later... 您可以将其包装在匿名函数中,以便仅在以后执行...

tdc.addEventListener("click", function() { ticker(0); }, false);

Have a look at the documentation here for some examples... 请查看此处的文档以获取一些示例...

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Search that page for "anonymous function" 在该页面上搜索“匿名功能”

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

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