このような 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/