我在页面中使用了两个下拉列表(第一个下拉类别和第二个下拉子类别),两个下拉列表都将动态加载,我将从第一个下拉列表中相应地选择一个值我必须将值加载到第二个下拉列表。我已经这样做了,但问题是它会第一次完成。
但是当我点击状态下拉列表中的其他选项时,它不会在第二个下拉列表中更新。
我的代码是: 这段代码是在加载页面时获取类别列表,即在 document.ready 下
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
这部分ajax是加载子分类
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
最佳答案
从我在您的代码中看到的情况来看,您总是添加新条目,但之前从不删除旧条目。因此,您的列表可能会随着新条目的增加而变得越来越长吗?在添加新条目之前尝试删除条目:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
根据我的经验,$.each 和 $.append 在处理一定数量的列表条目时会变得非常慢。我会使用 for() 和 createElement() 在 native javascript 中重写它。
关于javascript - 如何清除 select - html 标签下的选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522485/