前端技术 August 20, 2018

$.each用法及表单联动

Words count 3.7k Reading time 3 mins. Read count 0

元素遍历

HTML

<ul>
    <li id="one">1</li>
    <li id="two">2</li>
    <li id="three">3</li>
    <li id="four">4</li>
</ul>

JS

<script type="text/javascript">
    $('li').each(function (index,value) {
        console.log(index,$(value).attr('id'))
    })
</script>

说明:index为选择器的index的位置,value为当前的的元素(也可以使用‘this’选择器)

数组遍历

JS

var testArray = ['one','two','three','four'];
$.each(testArray,function (index,value) {
    console.log(index,value)
})

说明:index为数组的下角标,value为对应的值

对象遍历

JS

var testObject = {
    'one':'这是one',
    'two':'这是two',
    'three':'这是three'
};
$.each(testObject,function (index,value) {
    console.log(index,value)
})

说明 index为对象的key键,value为对象的值

https://shirukai.gitee.io/images/L2%25VYVZL8O3SIK@QDWD9XV6.png

表单联动

HTML

<select id="choseBase">
    <option>请选择</option>
</select>
<select id="choseSource">
    <option>请选择</option>
</select>
<select id="option">
    <option>

JS

var inputObject = {
    'MySQL': {
        '新建MySQL': ['选择mysql父节点', '选择mysql从节点'],
        '已有MySQL': ''
    },
    'ORACLE': {
        '新建oracle': ['选择oracle父节点', '选择oracle从节点'],
        '已有oracle': ''
    }
};
$.each(inputObject, function (key, value) {
    $('#choseBase').append('<option>' + key + '</option>')
});
var checkedBase, checkSource;
$('#choseBase').change(function () {
    $('#choseSource').empty();
    checkedBase = $('#choseBase option:selected').text();
    $('#choseSource').append('<option>请选择</option>');
    $.each(inputObject[checkedBase], function (key, value) {
        $('#choseSource').append('<option>' + key + '</option>')
    })
});
$('#choseSource').change(function () {
    $('#option').empty();
    checkSource = $('#choseSource option:selected').text();
    $('#option').append('<option>请选择</option>');
    $.each(inputObject[checkedBase][checkSource], function (key, value) {
        $('#option').append('<option>' + value + '</option>')
    })
})

https://shirukai.gitee.io/images/inputselect.gif

0%