所以我有一个资源列表或联系信息,每个“专业”都有很多资源或联系信息。
在左侧导航菜单上,我想创建一个“专业”列表,当单击该专业时,相关联系信息列表将显示在内容区域上。
听起来很简单,但我是初学者,正在寻找正确/最有效的方法来完成此任务。
这是源数据的样子(哪个更好?csv/json/mysql)
Table: people
┌────┬────────────────────┬─────────┬───────────┐─────────┐
| id | specialty| name | phone | url | address |
├────┼────────────────────┼─────────┤───────────┐─────────┐
| 0 | One | this | blah | www.x.com | 123 a st
| 1 | One | that | blah | www.x.com | 123 b st
| 2 | One | there | blah | www.x.com | 123 c st
| 3 | Two | the | blah | www.x.com | 123 d st
| 4 | Two | other | blah | www.x.com | 123 e st
└────┴────────────────────┴─────────┘───────────┘─────────┘
这是基本布局的 JFIDDLE:JSFIDDLE
所以我已经完成了数据和布局,但在以正确(最简单)的方式实现这一点时完全丢失了。
非常感谢所有帮助:)谢谢
最佳答案
我会这样做:
菜单 HTML 应该为空(ul 内没有 li 项),您将从 JS 填充它。
遍历数据数组并获得不同的专业:
var specialties = [], x;
for (x = 0; x < sampleData.length; ++x)
{
if ($.inArray(sampleData[x].specialty, specialties) < 0)
specialties.push(sampleData[x].specialty);
}
对于每个专业,您创建一个 li 元素并将其附加到 ul。此 li 元素将在自定义 data-specialty 属性中存储专业名称,并将附加 onclick 事件:
var ul = $("#menu");
for (x = 0; x < specialties.length; ++x)
{
var li = $(document.createElement("li"));
li.addClass("list-group-item");
li.attr("data-specialty", specialties[x]);
li.html(specialties[x]);
li.on("click", specialtyClicked);
ul.append(li);
}
onclick 函数遍历数据数组并与该专业的专家一起生成 HTML,然后将该 HTML 代码注入(inject)到 #contacts div 中:
function specialtyClicked()
{
// Remove active attribute from all menu items and add it to this one
$(".list-group-item").removeClass("active");
$(this).addClass("active");
// Get the specialty name
var specialty = $(this).attr("data-specialty");
// Create the HTML for the specialists
var output = "<h2>" + specialty + "</h2><br/>";
for (x = 0; x < sampleData.length; ++x)
{
var s = sampleData[x];
if (s.specialty != specialty)
continue;
output += "<h4>" + s.name + "</h4><p>" + s.address + "<br/>" + s.phone + " - " + s.url + "</p>";
}
$("#contacts").html(output);
}
这是一个完整的工作注释示例:https://jsfiddle.net/Lvq8a9me/8/我觉得看到代码就更容易理解了。
关于php - 基于导航菜单ajax加载json/mysql内容列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844520/