jq實現簡單的二級聯動下拉框

1 效果圖html

 

 

 

2 htmljquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>二級聯動下拉框</title>
    <script src="../js/lib/jquery-3.2.1.min.js"></script>
</head>
<body> 
    <div>
        <label>商品分類:</label>
        <select id="select-1" style="width:100px;">
        <option>--請選擇--</option>
        </select>
        </div>
        <div  style="margin-top:10px;">
        <label>具體商品:</label>
        <select style="width:100px;" id="select-2">
        <option>--請選擇--</option>
        </select>
        </div>
        <script src="../js/option.js"></script>
</body>
</html>

3 jqapp

$(function(){
    var arr1 = ['食材','家居','電子產品'];
    var arr2 = [['蔬菜','水果','調料'],['沙發','電池爐','冰箱'],['電腦','手機','充電寶']];
    for(let i=0;i<arr1.length;i++){
    $('#select-1').append('<option>'+arr1[i]+'</option>');
    }
    $('#select-1').change(function(){
    $('#select-2').children().not(':eq(0)').remove();
    var index = $(this).children('option:selected').index();
    var arr = arr2[index-1];
    for(let i=0;i<arr.length;i++){
    $('#select-2').append('<option>'+arr[i]+'</option>');
    }
    })
    })

 4 總結函數

,children();//獲取當前選中元素的一級子元素ui

.change();//綁定元素改變的處理函數this

.not();//從選中集合中剔除選中的元素,not裏面放篩選條件code

相關文章
相關標籤/搜索