javascript - 如何清除 select - html 标签下的选项值

标签 javascript jquery html ajax

我在页面中使用了两个下拉列表(第一个下拉类别和第二个下拉子类别),两个下拉列表都将动态加载,我将从第一个下拉列表中相应地选择一个值我必须将值加载到第二个下拉列表。我已经这样做了,但问题是它会第一次完成。

但是当我点击状态下拉列表中的其他选项时,它不会在第二个下拉列表中更新。

我的代码是: 这段代码是在加载页面时获取类别列表,即在 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/

相关文章:

javascript - jQuery 事件不绑定(bind)

javascript - 如果没有浏览器刷新,Skrollr 不会产生动画

html - 忽略部分 HTML 文档的样式表规则

javascript - 使用 Smarty 实现 Google Map Javascript API 时出现语法错误

javascript - 无法正确检查现有 cookie

javascript - 如何使用 AJAX 从多个网页调用 PHP 文件?

php - 如何在 Javascript 中加入带有自定义索引的数组项?

jquery - 使用 jquery 的产品列表。方法移除()

javascript - 数据库库

javascript - 使用 Javascript 从 html FORM 发送发布数据?