我只是想得到这样的 JSON 输出
{
"SW Reqs or Problem Analysis & Estimate": {
"Estimate_Days": "I",
"Performers": "am",
"Percent_Done": "so",
"Work_Done": "frustrated",
"Remaining_Work": "this",
"Comments": "won't"
},
"SW Requirements Doc ( in DOORS)": {
"Estimate_Days": "WORK",
"Performers": "PLEASE",
"Percent_Done": "HELP",
"Work_Done": "AAHHHHH",
"Remaining_Work": "HHHHHH",
"Comments": "HHHHHH!!!!"
}, ...etc
但是我的 json 看起来是这样的
{
"SW Reqs or Problem Analysis & Estimate": {
"Estimate_Days": "",
"Performers": "",
"Percent_Done": "",
"Work_Done": "",
"Remaining_Work": "",
"Comments": ""
},
"SW Requirements Doc ( in DOORS)": {
"Estimate_Days": "",
"Performers": "",
"Percent_Done": "",
"Work_Done": "",
"Remaining_Work": "",
"Comments": ""
},...etc
这是我的脚本,
$('#test').click(function(){
var content = {};
var inner = {};
$('.Data').each(function() {
var row = $(this).siblings(":first").text();
var id = $(this).attr('id').split('~');
var blah = id[0];
var html = $(this).html();
content[row] = inner;
inner[blah] = html;
});
var hey = JSON.stringify(content);
console.log(hey);
});
它遍历 <td>
在表中。如果我只是测试
console.log(html)
或 console.log(inner[blah])
它从 <td>
输出我需要的数据s 但出于某种原因,当我把它们显示为空白时,我尝试输出 content
.
是这条线的问题吗?
content[row] = inner;
inner[blah] = html;
这是创建对象的正确方法吗,content
,带 key ,row
, 值为另一个名为 inner
的对象有 key blah
和 html
的值?这不应该这么难。我必须错过一些东西。我读到当你有多维对象时你也可以使用 JSON,但我不明白为什么“Estimate_Days”之后的字符串是空白的。请帮忙。
编辑:这里有几行生成 html 的 php 循环:
foreach($group_results as $group){
echo '<tr><td class="Row_Title'.$group['Group_ID'].'">'.$group['Group_Name'].'</td>';
echo '<td class="Data" contenteditable="true" name="Estimate_Days~'.$group['Group_ID'].'" id="Estimate_Days~'.$group['Group_ID'].'"></td>';
echo '<td class="Data" contenteditable="true" name="Performers~'.$group['Group_ID'].'" id="Performers~'.$group['Group_ID'].'"></td>'; ...etc
最佳答案
更新:请注意,您发布的循环代码中的td
内容似乎是空的。这很可能就是为什么一切都是空白的原因,但它掩盖了对象引用的其他问题。
正如我提到的,您每次都在重复使用相同的 inner
实例。您真正想要做的是找到每个 Row_Title
单元格,然后为每个单元格,用剩余的 sibling 填充一行。我建议使用以下 javascript(用一些示例 HTML 来演示)。这遍历每个“行”并将外部数组设置为行标题的标题,然后循环遍历数据类型的每个兄弟并相应地设置该内部数组的各个属性。
$('#test').click(function(){
var content = {};
$('.Row_Title').each(function() {
var row = $(this).text();
content[row] = {};
$(this).siblings(".Data").each(function() {
var id = $(this).attr('id').split('~');
blah = id[0];
var html = $(this).html();
content[row][blah] = html;
});
})
var hey = JSON.stringify(content);
console.log(hey);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td class="Row_Title">Title 1</td>
<td class="Data" id="Field1~1">Field1Value1</td>
<td class="Data" id="Field2~1">Field2Value1</td>
<tr>
<td class="Row_Title">Title 2</td>
<td class="Data" id="Field1~2">Field1Value2</td>
<td class="Data" id="Field2~2">Field2Value2</td>
</tr>
</table>
<button id="test">
Go
</button>
关于javascript - 为什么我的内部对象中的值是空白的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111141/