【发布时间】:2017-06-19 22:48:27
【问题描述】:
我有一个具有复杂表格结构的网页。整个代码就在这里 --> (index.php)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php
// this turns the json object into an array
$json_string = file_get_contents("info.json");
$json = json_decode($json_string, true);
?>
<div id="scroll_box">
<table border="1" cellpadding="10" id="container">
<tr>
<td>
<table class="organizer">
<?php foreach($json as $key => $value): ?>
<!-- this is what needs to be repeated -->
<tr><td class="index"> <?php echo $key ?> </td></tr>
<thead class="sticky" align="center"><tr><th> <?php echo $value["name"] ?></th></tr></thead>
<tbody>
<tr>
<td>
<table class="spell_container">
<?php
foreach ($value["items"] as $key => $value) {
echo '<tr><td><table class="table-bordered spell_shorthand">'.
'<tr><td>Name</td><td class="name">'.$value["name"].'</td></tr>'.
'<tr><td>Type</td><td class="type">'.$value["type"].'</td></tr>'.
'</table>'.
'</td>'.
'<td class="description">'.$value["description"].'</td>'.
'<td><div class="btn-group"><button class="learn">Learn</button></div></td>'.
'</tr>';
}
?>
</table>
</td>
</tr>
</tbody>
<?php endforeach; ?>
</table>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(".learn").on('click', function(){
var the_name = $(this).closest("tr").find("table.spell_shorthand").find("td.name").text();
var the_type = $(this).closest("tr").find("table.spell_shorthand").find("td.type").text();
var the_description = $(this).closest("tr").find("td.description").text();
var the_index = $(this).closest("table.organizer").find("td.index").text();
console.log(the_name);
console.log(the_type);
console.log(the_description);
console.log(the_index);
});
</script>
</body>
</html>
并且正在使用的 JSON 数据看起来像这样 --> (info.json)
[
{
"name": "level0",
"items": [
{
"name": "item1",
"type": "type1",
"description": "this is item 1"
},
{
"name": "item2",
"type": "type2",
"description": "this is item 2"
},
{
"name": "item2",
"type": "type2",
"description": "this is item 3"
}
]
},
{
"name": "Level1",
"items": [
{
"name": "item4",
"type": "type4",
"description": "this is item 4"
},
{
"name": "item5",
"type": "type5",
"description": "this is item 5"
}
]
},
{
"name": "Level2",
"items": [
{
"name": "item6",
"type": "type6",
"description": "this is item 6"
}
]
}
]
现在。我在js脚本中的所有console.log语句都可以正常工作,除了处理“the_index”的语句......无论出于何种原因,它在真正应该返回索引(0、1、2)的所有实例时只是返回作为被单击按钮的父级的标题的索引。
我鼓励你拿这两个文件,亲自看看我在说什么。
任何关于为什么单击第一个索引 (0) 下的按钮会返回 (0 1 2) 的见解将不胜感激,谢谢。
【问题讨论】:
-
我猜你正在抓取所有你想要的最接近的 td.index。您是否考虑过在循环中索引主行(父行)?然后,您可以向按钮添加数据属性。 onclick 你会得到数据属性,它可以是你的主行ID,并且很容易访问里面的任何东西而没有太多麻烦。
-
我不知道该怎么做
标签: javascript php jquery json tree-traversal