【问题标题】:Javascript CreateElement buttonJavascript CreateElement 按钮
【发布时间】: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


【解决方案1】:

使用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 );
&lt;table id="tableOnline"&gt;&lt;/table&gt;

【讨论】:

  • 正是我需要的!非常感谢。
  • @Zhendos 很高兴为您提供帮助,如果有帮助,请考虑接受此答案:)
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2014-04-07
  • 2021-02-08
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多