我有一个小的JSON文件,看起来像这样
var myData = [{
"No": 1,
"Ticker": "WSI",
"Units": 72,
"Price In": 15,
"Entry Value": "",
},
{
"No": 2,
"Ticker": "DE",
"Units": 25,
"Price In": 15,
"Entry Value": "",
},
依旧......
另外一个生成简单表的脚本:
var myTable = '<table>';
myTable += '<tr>';
for (var x in myData[0]) {
myTable += '<th>' + x + '</th>';
}
myTable += '</tr>';
for (var i = 0; i < myData.length; i++) {
myTable += '<tr>';
for (var x in myData[i]) {
myTable += '<td>' + myData[i][x] + '</td>';
}
}
myTable += '</table>';
document.getElementById('jstable').innerHTML = myTable;
两个问题:
这样的事情不起作用:
var myData = [{
"No": 1,
"Ticker": "WSI",
"Units": 72,
"Price In": 15,
"Entry Value": myData.Units * myData.["Price In"],
},
谢谢
答案 0 :(得分:0)
var myData = [{
"No": 1,
"Ticker": "WSI",
"Units": 72,
"Price In": 15,
"Entry Value": "",
},
{
"No": 2,
"Ticker": "DE",
"Units": 25,
"Price In": 15,
"Entry Value": "",
}];
function getDynamicData(obj, key)
{
var value;
switch(x)
{
case "Entry Value" : value = obj["Units"] * obj["Price In"]; break;
default : value = obj[key];
}
return value;
}
function addListeners()
{
var elems = document.querySelectorAll("table td");
console.log(elems);
for(var i=0,n=elems.length; i<n;i++)
{
elems[i].addEventListener("click", editValue, true);
}
}
function editValue(elem)
{
var oldvalue = elem.target.textContent;
var input = document.createElement("input");
input.value = oldvalue;
var savebtn = document.createElement("button");
savebtn.textContent = "Save";
var cancelbtn = document.createElement("button");
cancelbtn.textContent = "Cancel";
savebtn.addEventListener("click",function(){
elem.target.textContent = input.value;
});
cancelbtn.addEventListener("click",function(){
elem.target.textContent = oldvalue;
});
elem.target.appendChild(input);
elem.target.appendChild(savebtn);
elem.target.appendChild(cancelbtn);
}
var myTable = '<table>';
myTable += '<tr>';
for (var x in myData[0]) {
myTable += '<th>' + x + '</th>';
}
myTable += '</tr>';
for (var i = 0; i < myData.length; i++) {
myTable += '<tr>';
for (var x in myData[i]) {
myTable += '<td>' + getDynamicData(myData[i],x) + '</td>';
}
}
myTable += '</table>';
document.getElementById('jstable').innerHTML = myTable;
addListeners();
<div id="jstable"></div>
要动态获取数据,最好使用getDynamicData()
等方法并处理switch中的案例。默认情况下,它不需要动态数据,而是返回
值。
点击后,你必须操纵DOM,即你必须将EventListener添加到该元素,操纵DOM元素并插入input
元素来编辑值,插入button
说保存/确定/提交,将eventListeners添加到这些元素,然后再次需要操作DOM。
您需要参考DOM Manipulation,addEventListeners
上的主题另外,请确保您通过跨浏览器支持了解所有内容。
我在示例中执行的addEventListeners将无法在IE上运行。它有另一种方式。你可能也想学习它。