您可以创建一个这样的 HTML 结构,您可以为每个流复制它。如果您的 HTML 中有多个流,这将很有帮助。
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
</div>
然后,假设您在数据库中的数据如下所示,
{
"Electronics": [
"VLSI",
"Tele Communication",
"Digital Circuits",
"Analog Communication"
],
"Medicine": [
"MBBS",
"MD",
"General Surgeon",
"Dental"
],
"Computers": [
"fuzzy logic",
"DataStructures",
"JavaScript"
]
}
您可以通过json["Electronics"]
- 这就是我们模拟ajax
呼叫的方式来获得价值。那么您的change
活动将如下所示。
$(".header [type=checkbox]").change(function () {
//remove all the older values - not necessary
$(".content").slideToggle(500, function () {
e.preventDefault();
$(this).remove();
});
//check if youre checking or unchecking
if (this.checked) {
//choosing header
var $header = $(this).closest(".header");
//building container element with ul for subjects in stream
var $content = $("<div/>", {
"class": "content"
}).append("<ul></ul");
var value = this.value;
//simulate ajax call -
var json = res[value];
//ajax here. result is json
//ajax success start - starting here , you could put this in the success function of ajax
//construct the lis - u could do it in any way
var $li = $.map(json, function (val, i) {
return "<li>" + val + "</li>";
});
//add the li to the uls
$content.find("ul").append($li);
//insert the content after specific header
$content.insertAfter($header).promise().done(function () {
//wait for the append to happen, else you wont get the animation
//open up the content needed
$content.slideToggle(500);
});
//ajax success end
}
});
基本上,我们正在添加一个元素,该元素在标题旁边动态地包含流中的主题。因此,如果您的 HTML 中有多个流,这将有所帮助。所以生成的 HTML 看起来像这样:
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
<div class="content">
<ul>
<li>Fuzzy Logic</li>
<!--more li's like this-->
</ul>
</div>
</div>
演示:http: //jsfiddle.net/hungerpain/Uyugf/