单击按钮时绑定数据表上的表

时间:2015-06-23 04:59:11

标签: jquery html onclick datatables

请帮助我,我想在用户点击按钮时绑定数据表上的表,但编码不起作用。我的代码如下所示:

<script src="jquery.js"></script>
<link href="css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').dataTable({
    "ajax": 'data.json',
    "paging":   false,
    "searching": false,
    "order": [[ 0, "asc" ]]
});
var t = $('#example').DataTable();
$('#addRow').on( 'click', function () {
    t.row.add([
        "1",
        "2",
        "3",
    ]).draw();
});
$("#button").click(function(e){
    $(".wrapper").html('<div><div id="addRow">add</div><table id="example" class="row-border hover" cellspacing="0" width="100%"><thead><tr><th align="left">title 1</th><th align="left">title 2</th><th align="left">title 3</th></tr></thead></table></div>');
});
});
</script>
<body>
<div class="wrapper"></div>
<div class="button"><input name="tbSubmit" type="button" value="click this button" id="button"></div>

我的data.json如下所示:

{
    "data": [
        [
            "1.1",
            "1.2",
            "1.3"
        ],
        [
            "2.1",
            "2.2",
            "2.3"
        ],
        [
            "3.1",
            "3.2",
            "3.3"
        ]
    ]
}

如果此代码不是单击html,则代码将运行,但在类包装器中如下所示:

$("#button").click(function(e){
    $(".wrapper").html('');
});

<div class="wrapper"><div><div id="addRow">add</div><table id="example" class="row-border hover" cellspacing="0" width="100%"><thead><tr><th align="left">title 1</th><th align="left">title 2</th><th align="left">title 3</th></tr></thead></table></div></div>

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

您尝试在事件存在之前将事件绑定到#addRow。只有在您点击#button后,才会将其添加到.wrapper

要使事件绑定起作用,#addRow需要已经在DOM上。或者......你可以绑定到一个祖先作为听众,如下所示:

$('.wrapper').on('click', '#addRow', function() { /*etc*/ });

答案 1 :(得分:0)

它解决了,我只是改变了这样的位置:

$(".wrapper").html('<div><div id="addRow">add</div><table id="example" class="row-border hover" cellspacing="0" width="100%"><thead><tr><th align="left">title 1</th><th align="left">title 2</th><th align="left">title 3</th></tr></thead></table></div>');
        var table = $('#example').dataTable({
            "ajax": 'data.json',
            "paging":   false,
            "searching": false,
            "order": [[ 0, "asc" ]]
        });
        var t = $('#example').DataTable();
        $('#addRow').on( 'click', function () {
            t.row.add([
                "1",
                "2",
                "3",
            ]).draw();
        });