【发布时间】:2017-07-14 03:53:59
【问题描述】:
我遇到了一个困扰了几个小时的问题。 上下文是,我需要在 JavaScript 中创建一个带有动作侦听器的按钮并将其添加到表格中。
这是我的代码
var _button = document.createElement("button");
_button.data = _a;
_button.innerHTML = 'click me';
_button.onclick = function()
{
alert("hello, world");
}
var table = document.getElementById("tableOnline");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var _weakbutton = _button.outerHTML;
_weakbutton.onclick = function()
{
alert("hello, world");
}
cell1.innerHTML = "h";
cell2.innerHTML = "o";
cell3.innerHTML = _weakbutton;
如果我添加创建按钮并将其添加到主体上(没有弱按钮),代码可以工作,但我怎样才能让它在表格中工作?
亲切的问候, 真多斯。
编辑: 由于要求,这里是我们谈论的表格。
<div class = "container">
<div class = "table">
<thead id = "thead">
<tr>
<th> firstname <th>
<th> lastname </th>
<th> organisation </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
【问题讨论】:
-
请同时显示相关的 (minimal reproducible example) HTML。
-
仅供参考:
_weakbutton.onclick,没有设置点击处理程序,因为_weakbutton只是一个string变量。 -
如果我将onclick添加到按钮上并制作一个weakButton,onclick事件就消失了。
-
另外,
table.insertRow(1);仅在表中已有行的情况下才有效,the optional argument 是您想要新行的索引。该参数不能大于当前存在的行数。检查您的控制台是否有错误
标签: javascript button createelement