【问题标题】:html and dom button sequence creationhtml和dom按钮序列创建
【发布时间】:2013-02-08 13:11:22
【问题描述】:

我正在尝试弄清楚如何使用按钮来创建显示在所选按钮前面的新按钮。有三个按钮和一个“插入”按钮。我希望能够单击按钮 1,然后插入并在其前面出现一个新按钮。按钮 2 和 3 也会发生同样的情况。

我注意到在我的代码中单击按钮会自动在表格中的单元格 0 处创建一个新按钮。除了接受“插入”按钮可以使用的用户输入,我不希望按钮实际执行任何操作。

请帮忙,我卡住了。

我目前的代码是:

<html>
<head>
<title>Button Sequence Creation</title>
<script>
function displayResult()
{
var firstRow=document.getElementById("myTable").rows[0];
var x=firstRow.insertCell();
x.innerHTML="New"
}
</script>
</head>
<body>
<h1>Button Sequence Creation</h1>
<hr>
<table id = "myTable" border="1">
  <tr>
        <td>
    <input type="button" value="button1" name ="button1" onclick="displayResult()"></td>
        <td>
    <input type="button" value="button2" name ="button2" onclick="displayResult()"></td>
        <td>
    <input type="button" value="button3" name ="button3" onclick="displayResult()"></td>
  </tr>
</table>
<br>
<button type="button" onclick="displayResult()">Insert</button>
</body>
</html>

【问题讨论】:

    标签: html xml dom button html-table


    【解决方案1】:

    不确定您希望“插入”按钮如何工作。但下面的代码有效。

    <html>
    <head>
      <title>Button Sequence Creation</title>
      <script>
        function displayResult(obj){
          var firstRow=document.getElementById("myTable").rows[0];
          var newButton = document.createElement('input');
          newButton.type = 'button';
          newButton.value = "New";
    
          var newTD = document.createElement('td');
          newTD.appendChild(newButton);
    
          obj.parentNode.parentNode.insertBefore(newTD, obj.parentNode);
        }
      </script>
    </head>
    <body>
      <h1>Button Sequence Creation</h1>
      <hr>
        <table id = "myTable" border="1">
          <tr>
            <td>
              <input type="button" value="button1" id="button1" name ="button1" onclick="displayResult(this)">
            </td>
            <td>
              <input type="button" value="button2" id="button2" name ="button2" onclick="displayResult(this)">
            </td>
            <td>
              <input type="button" value="button3" id="button3" name ="button3" onclick="displayResult(this)">
            </td>
          </tr>
       </table>
       <br>
       <!--button type="button" onclick="displayResult()">Insert</button-->
    </body>
    </html>
    

    【讨论】:

    • 保罗,这比我尝试做的还要好!我看到您在对象之间创建了父子关系。您还为按钮提供了自己的 ID。因此,您只需创建 newButton 函数,而不是插入新单元格,对吧?
    • 没错。创建一个新按钮,然后附加到新的 td。然后引用你希望插入新 DOM 元素的父元素和你想在之前插入的子元素。
    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多