使用HTML和Java脚本在表中动态添加Button

时间:2016-02-08 09:48:29

标签: javascript jquery html

enter image description here Hi I have Table, I have to add a Button, beside the +, when ever I click on it.

代码无效。我不明白为什么。



function addProject() {
        var r = $('<input/>').attr({
            type: "button",
            id: "field",
            value: 'Project'
        });
       $("#idProject").parent().append(r);
    }
&#13;
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
</thead>
<tbody>
    
    <tr>

        <td style="text-align:center; width:8%"></td>
          <td style="text-align:center; width:8%"><input id="idProject" type="button" style="border:1px solid grey;text-align:center;background-color:#E0EEEE" value="+" onclick=addProject() /></td>
    </tr>
    
</tbody>
 </table>
  </html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

使用以下代码view demo

   <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to make a BUTTON element with text.</p>

    <button onclick="createbtn()">Create</button>

    <script>
    function createbtn() {
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("CLICK ME");
        btn.appendChild(t);
        document.body.appendChild(btn);
    }
    </script>

    </body>
    </html>

http://codepen.io/anon/pen/vLQEEX

答案 1 :(得分:0)

因为您说要显示+旁边的按钮...将其添加到同一个td。

1)添加到输入的td,如$(event.srcElement).parent().append(r);

function test() {
        var r = $('<input/>').attr({
            type: "button",
            id: "field",
            value: 'Project'
        });
    
    $(event.srcElement).parent().append(r);
    }
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
</thead>
<tbody>
    
    <tr>

        <td style="text-align:center; width:8%"></td>
        <td style="text-align:center; width:8%"><input id="idProject" type="button" style="border:1px solid grey;text-align:center;background-color:#E0EEEE" value="+" onclick=test() /></td>
    </tr>
    
</tbody>
 </table>
  </html>