如何在jQuery上更改下拉菜单属性

How to change dropdown menu attributes on jQuery?

本文关键字:下拉菜单 属性 jQuery      更新时间:2023-09-26

我的问题是,我有2下拉框,我想通过第一个值改变第二个下拉框。例如:如果用户在第一个下拉菜单中选择了"Apple",第二个下拉菜单应该会立即出现"iPhone"answers"iPad"选项。如果客户改变主意,选择了"Microsoft",则应删除"iPhone"answers"iPad"的值,取而代之的是"Windows"answers"Office"。我怎样才能让它工作?谢谢。

HTML:

<select name="brand" id="brand" onChange="populateSecond(this.value);">
    <option value="">----------------</option>
    <option value="1">Apple</option>
    <option value="2">Microsoft</option>
</select>
<select id="model">
    <option value="">----------------</option>
</select>
jQuery:

$(document).ready(function() {
    $("#brand").change(function(populateSecond(id)) {
            if(id == 1){
                $('select[id=model]').append('<option value="a">iPhone</option>');   
                $('select[id=model]').append('<option value="a">iPad</option>');
            }if(id == 2){
                $('select[id=model]').append('<option value="b">Windows</option>');    
                $('select[id=model]').append('<option value="b">Office</option>'); 
            }
    });
});

问题:http://jsfiddle.net/w6E88/6/

从html中删除onChange,并像这样做!你已经使用Jquery onchange,不需要给onChange到你的HTML,如果你需要从第一个下拉列表中选择的值,你可以简单地使用this.value来获得它,并对你的第二个下拉列表进行必要的更改。

<select name="brand" id="brand">
    <option value="">----------------</option>
    <option value="1">Apple</option>
    <option value="2">Microsoft</option>
</select>
<select id="model">
    <option value="">----------------</option>
</select>

JQUERY

$(document).ready(function() {
$("#brand").change(function() {
       var id=this.value;
        if(id == 1){
             $('#model').html("");
            $('#model').append('<option value="a">iPhone</option>');   
            $('#model').append('<option value="a">iPad</option>');
        }else if(id == 2){
            $('#model').html("");
            $('#model').append('<option value="b">Windows</option>');    
            $('#model').append('<option value="b">Office</option>'); 
        }
        else{
         $('#model').html("");
         $('#model').append('<option value="">----------------</option>')
        }
});
});

这是实现您想要的功能的另一种jQuery方法(注释并解释)

添加了bootstrap类来选择元素。

<select id="mainCategorySelect" name="mainCategorySelect" class="form-control">
    <option>Select category</option>
</select>
<select id="subCategorySelect" name="subCategorySelect" class="form-control"></select>

JS

// Wait for the dom to be ready
$(function () {
    // For the sake of this example our business and products are arrays
    var businesses = ["Microsoft","Apple"],
        msProducts = ["Microsoft Phone","Microsoft Office","Microsoft Windows 10"],
        appleProducts = ["Apple iPhone","Apple iPad","Apple iPod","Apple iSomething"],
        // Declare variables for the select elements
        mainCategorySelect = $('#mainCategorySelect'),
        subCategorySelect = $('#subCategorySelect');
    // Iterate thorugh businesses and populate the main select element
    for (var i = 0; i < businesses.length; i++) {
        mainCategorySelect.append("<option value='"+businesses[i]+"'>"+businesses[i]+"</option>");
    }
    // using jQuery .on('change')
    mainCategorySelect.on('change', function() {
        // Always clear the sub category select when main select element value is changed
        subCategorySelect.empty();
        // Retrieve the value of the main select element
        var business = $(this).val();
        // if else statement to deside which products to list in the sub category select element
        if (business == "Microsoft") {
            // if Microsoft then iterate through the msProducts array and append the values as option elements to the sub category select element
            for (var i = 0; i < msProducts.length; i++) {
                subCategorySelect.append("<option value='"+msProducts[i]+"'>"+msProducts[i]+"</option>");
            }
        } else if(business == "Apple") {
            // if Apple then iterate through the appleProducts array and append the values as option elements to the sub category select element
            for (var i = 0; i < appleProducts.length; i++) {
                subCategorySelect.append("<option value='"+appleProducts[i]+"'>"+appleProducts[i]+"</option>");
            }
        }
        // When the user changes the value of the sub category select element the do something with it
        subCategorySelect.on('change', function() {
            alert($(this).val());
        });
    });
});

这里是一个工作小提琴:http://jsfiddle.net/kagLhpka/

你的HTML代码中已经有了onChange="populateSecond(this.value);",在JS中也不需要.change

可以在第一次调用populateSecond之前完全定义函数;或者只使用jQuery方法。这里我只给出了jQuery的结果:

$(document).ready(function () {
    $("#brand").on('change', function (id) {
        if (id == 1) {
            $('select[id=model]').append('<option value="a">iPhone</option>');
            $('select[id=model]').append('<option value="a">iPad</option>');
        } else {
            $('select[id=model]').append('<option value="b">Windows</option>');
            $('select[id=model]').append('<option value="b">Office</option>');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="brand" id="brand">
    <option value="">----------------</option>
    <option value="1">Apple</option>
    <option value="2">Microsoft</option>
</select>
<select id="model">
    <option value="">----------------</option>
</select>

PS:我更喜欢使用.on('change', handler)方法而不是.change

这是结构化的方法。

    var childData = {
        apple: ["iPhone", "iPad"]  ,
        ms: ["Windows", "Office"]
    };
    $("#brand").change(function () {
        var newData = childData[this.value];
        var element = $("#model").empty();
        element.append('<option>----------------</option>');
        $.each(newData, function(i, val) {
            element.append('<option value='+i+'>'+val+'</option>');
        });
    });

检查此提琴:http://jsfiddle.net/soundar24/w6E88/11/

如果产品线扩展到一定数量,使用显式条件进行验证将使将来难以维护。使用某种形式的数组是一种更好的方法,正如其他人所展示的那样。

另外,虽然jQuery是一个很棒的库,但不要忘记了普通的JavaScript。如果编码得好,即使看起来比较复杂,纯JavaScript应该比对应的jQuery运行得更快。考虑到这一点,这里有另一个解决方案,这次是"或多或少"的纯JavaScript——我留下了on ready。

<select name="brand" id="brand">
  <option value="-1">--------------------</option>
  <option value="apple">Apple</option>
  <option value="microsoft">Microsoft</option>
</select>
<select id="model">
  <option value="-1">--------------------</option>
</select>
JavaScript

var products = {
  apple: [
    { name: "iPhone 6 Plus", model: "iphone_6plus" },
    { name: "iPhone 6", model: "iphone_6" },
    { name: "iPhone 5s", model: "iphone_5s" },
    { name: "iPhone 5c", model: "iphone_5c" }
  ],
  microsoft: [
    { name: "Windows 10", model: "windows_10" },
    { name: "Windows 8", model: "windows_8" },
    { name: "Office 2015", model: "office_2015" },
    { name: "Office 2014", model: "office_2014" }
  ]
};
function create_option(text, value) {
  var option = document.createElement("option");
  var txt = document.createTextNode(text);
  option.value = value;
  option.appendChild(txt);
  return option;
}
function populate_model(selection) {
  var select = document.getElementById("model");
  var i, l;
  if ((selection == -1) || (products[selection] === undefined))
    return false;
  while (select.lastChild)
    select.removeChild(select.lastChild);
  select.appendChild(document.createElement("option").appendChild(document.createTextNode("--------------------")));
  for (i = 0, l = products[selection].length; i < l; i++)
    select.appendChild(create_option(products[selection][i].name, products[selection][i].model));
}
$(document).ready(function() {
  var brand = document.getElementById("brand");
  brand.onchange = function() {
    populate_model(this.options[this.selectedIndex].value);
  };
  brand.value = -1;
});

我也更新了你的JSFiddle: http://jsfiddle.net/w6E88/13/