我想通过单击按钮创建一个表,我需要将表保存到数据库。这是创建表的代码,但我认为这是如此之长,我怎样才能快速创建它?
var div = document.createElement("div");
var table1 = document.createElement("table");
var table2 =document.createElement("table");
var thead = document.createElement("thead");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
var th3 = document.createElement("th");
th1.innerHTML="Count";
th2.innerHTML="Date";
th3.innerHTML="Price";
document.body.appendChild(div);
div.appendChild(table1);
div.appendChild(table2);
table2.appendChild(thead);
thead.appendChild(th1);
thead.appendChild(th2);
thead.appendChild(th3);
答案 0 :(得分:0)
如果代码太长,我建议在未显示的div中创建一个html表结构。然后,当用户单击该按钮时,您可以
您的代码将如此(克隆明智):
jQuery的:
$('#myButton').on('click', function(){
$(document.body).append($('original').clone());
});
使用Javascript:
document.getElementById('myButton').onclick = function(){
document.body.appendChild(document.getElementById('original').cloneNode());
}
这是你可以隐藏的html表。
<div style="display: none;">
<table id="original">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
这大大减少了您的javascript代码。
答案 1 :(得分:0)
如果你想进行一些增强,你可以使用像muchtache.js这样的预编译模板:
<table>
<tr>
<th> Count </th>
<th> Date </th>
<th> Price </th>
</tr>
{{#jsonObject}}
<tr>
<td>{{Count1}}</td>
<td>{{Date1}}</td>
<td>{{Price1}}</td>
</tr>
{{/jsonObject}}
</table>
在javascript中,您可以将您的javascript jsonobject
写为:
jsonobject : [{
count1 : 1,
date1 : 12/12/2012,
price1 : 100
},
{
count1 : 2,
date1 : 12/12/2013,
price1 : 200
}
]
获取完整的更多示例访问Json Object into Mustache.js Table
答案 2 :(得分:0)
以下功能可能有所帮助:
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
以下是如何使用它:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<table></table>'
+ '<table>'
+ '<thead>'
+ '<th>Count</th>'
+ '<th>Date</th>'
+ '<th>Price</th>'
+ '</thead>'
+ '</table>'
+ '</div>'
));
现场演示:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<p>Paragraph.</p>'
+ '<ul>'
+ '<li>Item 1.</li>'
+ '<li>Item 2.</li>'
+ '<li>Item 3.</li>'
+ '</ul>'
+ '</div>'
));
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
&#13;