使用Jquery动态生成表

时间:2017-07-05 18:34:01

标签: javascript jquery jquery-ui

我使用JQuery版本1.8.4和jquery-ui-1.9.2

我有这个数组:

window.mapData.Layers = [{id:1,Title:water}{id:2,Title:land}{id:4,Title:data}{id:1,Title:info}]

我尝试使用一些文本和两个按钮创建表格。

表中的每一行都必须显示title来自图层数组的对象的属性 以及两个按钮editdelete。每个按钮都必须在点击时将属性id作为参数发送给处理程序。

以下是代码:

(function () {
    var content = $('<table>')
    $(window.mapData.Layers).each(function (i, j) {
        content += '<tr><td>' + j.Title + '</td><td>' + $('<button/>')
    .text('Edit').onClick('eventHandler').params('j.id') +'</td>'+'<td>'+$('<button/>').text('Delete').onClick('eventHandler').params('j.id')+'</td>'+'</td></tr>'})

        $('#vectorLayerslist').append(content);
    }())

以下是我得到的结果:

water   [object Object] [object Object]
land    [object Object] [object Object]
data    [object Object] [object Object]
info    [object Object] [object Object]

但它不起作用。正如你上面所看到的,它只生成文本而不生成按钮。 知道为什么按钮没有生成?如果有更优雅的方式来实现我的任务?

1 个答案:

答案 0 :(得分:1)

将表构建为字符串,然后将字符串追加一次。

jQuery's event propagation用于动态创建的元素。

&#13;
&#13;
var Layers = [{id:1,Title:'water'},{id:2,Title:'land'},{id:4,Title:'data'},{id:5,Title:'info'}];

var vectorLayersList = $('#vectorLayerslist');

// build the table
var content = '<table>';
    content += '<thead><tr>';
    content += '<th>Title</th>';
    content += '<th colspan="2">Actions</th>';
    content += '</tr></thead><tbody>';
$.each(Layers, function () {
    // we'll store the ID in HTML5 data-attribute for later
    content += '<tr data-id="' + this.id + '">'; 
    content += '<td>' + this.Title + '</td>';
    // give classes to your buttons for later
    content += '<td><button type="button" class="edit">Edit</button></td>'; 
    content += '<td><button type="button" class="delete">Delete</button></td>';
    content += '</tr>';
});
content += '</tbody></table>';

// append the table once
vectorLayersList.append(content);

// attach event handlers
vectorLayersList.on('click', '.edit', function () {
    var id = $(this).closest('tr').data('id');
    console.log('editing ' + id);
});

vectorLayersList.on('click', '.delete', function () {
    var id = $(this).closest('tr').data('id');
    console.log('deleting ' + id);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="vectorLayerslist"></div>
&#13;
&#13;
&#13;

相关问题