javascript - 如何在 HTML 的特定部分添加和删除 'table'?

标签 javascript jquery html

如何在每次点击添加新表...按钮时添加在START:在此处添加此表之间添加HTML内容>END:在此添加此表

同时,如果我单击删除按钮,它应该从 HTML 中删除该表。不幸的是它不起作用。

我的 HTML:

<div class="col">
    <div class="row">

      <table class="table table-bordered">
        <a class="btn" id="AddNewTable" >Add NEW table...</a>
      </table>

    <!-- START: add here this table -->

      <table>
        <tr>
            <th>This is a new table...</th>
            <th><button class="remove">Remove this table</button></th>
        </tr>
      </table>

    <!-- END: add here this table -->

      <table class="table table-bordered">
        <a class="btn">Different Content</a>
      </table>

    </div>
</div>

我的 JavaScript:

var html = "";

html += '<table>';
html += '<tr>';
html += '<th>This is a new table...</th>';
html += '<td><button class="remove">Remove this table</button></td>';
html += '</tr>';
html += '</table>';

$(function() {
    $('tbody').sortable();

    $('#AddNewTable').click(function(){
        $('tbody').append(html);
    });

    $(document).on('click', '.remove', function() {
        $(this).parents('tr').remove();
    });

    $('#getValues').click(function(){
        var values = [];
        $('input[name="name"]').each(function(i, elem){
            values.push($(elem).val());
        });
        alert(values.join(', '));
    });
});

最佳答案

根据您发布的内容,页面上没有任何 tbody 元素。因此,每次您单击添加新表...时,它都会将html内容添加到任何地方。

关于javascript - 如何在 HTML 的特定部分添加和删除 'table'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918518/

相关文章:

javascript - 动态创建的元素上的事件绑定(bind)?

javascript - jQuery 中第一个函数完成后,.click 中的新函数

jquery - 当我在当前选定的 div 之前或之后插入一个新的空白 div 时,jquery 中的选项卡高度突然增加了吗?

javascript - 如何使用/解析 JavaScript 字符串中的 HTML 实体和 Unicode 字符

javascript - 为什么 javascript 显示 "Uncaught SyntaxError: Identifier ' Common' has already been declared after making javascript class object"in console?

javascript - 无法解析包含单引号的 json 数据

html - 更改选择元素的占位符文本的颜色

javascript - 有没有办法在 HTML5 中播放 mpeg 视频?

javascript - CKEditor5 文本对齐

javascript - OAuth2 访问源错误