我有一个问题,我已经忍受了几个小时了。上下文是,我需要在JavaScript中制作一个带有action listener的按钮,并将其添加到一个表中。
下面是我拥有的代码
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;如果我添加创建按钮并将其添加到主体上(没有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>发布于 2017-02-23 23:24:12
使用var _weakbutton = _button.cloneNode(true);创建该按钮的副本,而不是var _weakbutton = _button.outerHTML;。这将在原有按钮的基础上创建一个新按钮。
因为这现在是一个按钮节点,所以您不能使用cell3.innerHTML = _weakbutton;添加它,而必须使用cell3.appendChild( _weakbutton );
因此,对于您的代码,它将是
var _button = document.createElement("button");
_button.data = "hi";
_button.innerHTML = 'click me';
_button.onclick = function()
{
alert("hello, world");
}
var table = document.getElementById("tableOnline");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var _weakbutton = _button.cloneNode(true)
_weakbutton.onclick = function()
{
alert("hello, world");
}
cell1.innerHTML = "h";
cell2.innerHTML = "o";
cell3.appendChild( _weakbutton );<table id="tableOnline"></table>
https://stackoverflow.com/questions/42419614
复制相似问题