我有三个菜单:学院,部门和课程。单击学院时,将显示属于该学院的部门列表。单击部门时,将显示属于该部门的程序列表。
我的问题是,当我点击一个新的学院时,部门会在第二个列表中重新填充,但我无法在第三列中找到程序来清除。我已经尝试过.nextAll()和.siblings()以及诸如此类的一些不同的东西,但还没有任何工作。
这是HTML:
<div class="row">
<div class="col-xs-4">
<h4>Colleges</h4>
<ul class="colleges-menu">
<?php CommonFunctions::getCollege('list'); ?>
</ul>
</div>
<div class="col-xs-4">
<h4>Departments</h4>
<ul id="departments" class="colleges-menu">
</ul>
</div>
<div class="col-xs-4">
<h4>Programs</h4>
<ul id="programs" class="colleges-menu">
</ul>
</div>
和JQuery:
function ajaxLists(){
var entity = '.' + $(this).attr('class');
var nextEntity;
var value;
var data;
switch(entity){
case '.college':
nextEntity = '#departments';
value = $(this).val();
data = {list_college: value};
break;
case '.departments':
nextEntity = '#programs';
value = $(this).val();
data = {list_departments: value};
break;
default:
break;
}
//this should ONLY run if we are selecting a college or department
if(entity == '.college' || entity == '.departments'){
$("body").css("cursor", "progress");
$.ajax({
url: "sort_college.php",
type: "post",
data: data,
success: function(info){
$(nextEntity).html('');
$(nextEntity).append(info);
console.log(info);
},
error: function(){
alert("there's an error with AJAX");
}
}).done(function(){
$("body").css("cursor", "default");
}); //end ajax
}
}
答案 0 :(得分:0)
正如您所提到的,您的代码应该适合将来添加的其他元素,您需要确保不依赖于硬编码的ID,类等。
这应该可以解决你的问题,或者至少为你提供一个良好的基础:
$(function () {
$('.col-xs-4 .colleges-menu').on('click', 'li', function () {
// Go up in this element parents until you reach the div.
// Then you go to its next sibling and grab the ul.
var nextEntity = $(this).parents('.col-xs-4').next().find('ul');
// Self explanatory.
var value = $(this).val();
// Variable to store the data.
var data = {};
// If there's a nextEntity element, it means you didn't reach the last
// set of options.
if (nextEntity) {
// Creating a property for data that is based in a variable.
data["list_" + nextEntity.attr("id")] = value;
$("body").css("cursor", "progress");
$.ajax({
url: "sort_college.php",
type: "post",
data: data,
success: function (info) {
nextEntity.html('');
nextEntity.append(info);
console.log(info);
},
error: function () {
alert("there's an error with AJAX");
}
}).done(function () {
$("body").css("cursor", "default");
});
}
});
});