使用javascript动态删除元素

时间:2016-09-21 13:00:48

标签: javascript php html dynamic element

我有一个带有创建表的函数的javascript。现在我希望每次再次按下按钮时更新/替换表格。我已经尝试了一些我在网上找到的解决方案但似乎没有做我想做的事。

的javascript

  //Updates table
function myFunction(jsonObject) {

//Build array from the jsonObject
var customers = new Array();
var jsonArr = jsonObject['log'];
for(var i in jsonArr){
    customers.push((jsonArr[i]['date']) );
    customers.push((jsonArr[i]['time']) );
    customers.push((jsonArr[i]['temp']) );
    customers.push((jsonArr[i]['humidity']) );
}



//Remove existing tables.-----------------------THIS HAS NO EFFECT!
var myNode = document.getElementById('logDiv');
while (myNode.hasChildNodes()) {
        alert("logDiv has nodes, removing them now!")
        myNode.removeChild(myNode.firstChild);
}
//----------------------------------------------THIS HAS NO EFFECT!



var container = document.getElementById('logDiv');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className = "sortable";

//Adds table headers
var headers = ["Date", "Time", "Temp", "Hum"]
var row1 = document.createElement('tr');
for (var b = 0; b < 4; b++) {
    var cell = document.createElement('th');
    cell.textContent = headers[b];
    row1.appendChild(cell);
    counter++;
}
tbody.appendChild(row1);

var counter = 0;
// loop and create rows
for (i = 0; i < customers.length/4; i++) {
    var values = customers[i];
    var row = document.createElement('tr');

    // loop and create columns
    for (var b = 0; b < 4; b++) {
        var cell = document.createElement('td');
        cell.textContent = customers[counter];
        row.appendChild(cell);
        counter++;
    }
    tbody.appendChild(row);
}
table.appendChild(tbody);
container.appendChild(table);
}

HTML / PHP的

   <?php
    $logLines = file('../../../home/shares/flower_hum/humid.log');
    $entries = array_map("clean",$logLines);
    $finalOutput = ['log'  => $entries];
    function clean($string){
        return json_decode(rtrim(trim($string),','),true);
    }

    $json = json_encode($finalOutput);
    ?>

<html>
    <head>
        <script src="script.js" type="text/javascript"></script>
        <script src="sorttable.js" type="text/javascript"></script>
        <link rel="stylesheet" type="text/css" href="style.css">

        <meta charset="UTF-8">
        <title>Antgus</title>
    </head>
    <body>
        <button id="btnGenerate" type="button" onclick='myFunction(<?php echo $json ?>)'>Generate log</button>
        <br><br>
        <div id="logDiv"></div>
    </body>
</html>

0 个答案:

没有答案