为什么innerHTML附加一个逗号

时间:2014-08-04 18:24:46

标签: javascript html dom

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="media/js/jquery.js"></script>
<script>
var table = "";
var example_array = [];

function tablething() {
    index = document.getElementById("location").value;
    value = document.getElementById("input_value").value;
    addRow(index,value);
}

function addRow(index,value){
     var rowBeg = "<tr><td>";
     var rowEnd = "</td></tr>";

     value = rowBeg + value + rowEnd;
     example_array.splice(index,0,value);
     console.log(example_array);
     table.innerHTML = example_array;
     console.log(table.innerHTML);
}

$( document ).ready(function() {
    table = document.getElementById("example");
    example_array = new Array();
});
</script>
</head>
<body>

<table id="example">
</table>

Location: <input type="text" id="location"/>
Value: <input type="text" id="input_value"/>
<button onclick="tablething()">Add</button>

</body>
</html>

控制台中的结果是

Array [ "<tr><td>0</td></tr>" ] dyna_row.html:21
"<tbody><tr><td>0</td></tr></tbody>" dyna_row.html:23
Array [ "<tr><td>0</td></tr>", "<tr><td>1</td></tr>" ] dyna_row.html:21
"<tbody><tr><td>0</td></tr><tr><td>1</td></tr></tbody>," dyna_row.html:23
Array [ "<tr><td>0</td></tr>", "<tr><td>1</td></tr>", "<tr><td>2</td></tr>" ] dyna_row.html:21
"<tbody><tr><td>0</td></tr><tr><td>1</td></tr><tr><td>2</td></tr></tbody>,," dyna_row.html:23
Array [ "<tr><td>0</td></tr>", "<tr><td>1</td></tr>", "<tr><td>2</td></tr>", "<tr><td>3</td></tr>" ] dyna_row.html:21
"<tbody><tr><td>0</td></tr><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></tbody>,,,"

我怀疑是

  1. 为什么每次调用方法addRow时,此代码都会在innerHTML的末尾添加逗号?

  2. example_array.join(“”)似乎达到了我想要做的但是toString方法也没有返回与join方法相同的内容?

1 个答案:

答案 0 :(得分:5)

当数组转换为字符串时,它会在值之间添加逗号。

这将使用值之间的空格而不是

table.innerHTML = example_array.join(" ");