使用JS将行添加到html表

时间:2013-12-07 21:22:18

标签: javascript html5

我正在尝试从我的javascript文件中获取一些数据并将其放入我的html文件中的新行和列中。我认为问题可能与我的脚本在我的html文件中的表之前关闭有关。我目前在我的html文件中有一个表格,如下所示:

<div id="map" style="width: 700px; height: 700px"></div>
            <script src="js/mapping.js"></script>


            <div id="tablebody">
            <p>
                <b>List of Nearby Locations</b>
            </p>
                <table class="table table-stripped">
                    <tbody>
                        <tr>
                            <th>Name</th>
                            <th>Address</th>
                        </tr>
                        <tr>
                            <td>John Smith</td>
                            <td>1500 Pennsylvania Ave</td>
                        </tr>
                    </tbody>
                </table>
            </div>

和JS代码看起来像这样:

service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);


    function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {

            for (var i = 0; i < results.length; i++) {
                createMarker(results[i]);
                alert("name: " + results[i].name + ", Address:" + results[i].vicinity);
                $('#tablebody tr:last').after('<tr>"Name: " + results[i].name + ", Address: " + results[i].vicinity</tr>');
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

尝试以javascript为基础:

  tableObject.insertRow(index)

或jQuery

 $('#tablebody').append('<tr>"Name: " + results[i].name + ", Address: " + results[i].vicinity</tr>');

答案 1 :(得分:1)

您在表行中缺少表格单元格,我假设您希望将名称和附近地址连接到代码中,而不仅仅是在表格中显示Javascript代码:

$('#tablebody tr:last').after('<tr><td>Name: ' + results[i].name + ', Address: ' + results[i].vicinity + '</td></tr>');

或者行中有两个单元格:

$('#tablebody tr:last').after('<tr><td>' + results[i].name + '</td><td>' + results[i].vicinity + '</td></tr>');