欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Jquery动态列

程序员文章站 2022-06-12 22:21:37
...

看到有人写的一个JQUERY动态列, 值得参考, 特转发下来

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
body {
    margin: 50px 100px;
}
#dataTable tr td{
    width: 100px;
    display: none;
}
.theader {
    background:#A4D4FC;
}

</style>
<script src="jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
//init page
var columns = ['Column A', 'Column B', 'Column C', 'Column D', 'Column E', 'Column F', 'Column G'];
for(var i=0; i < columns.length; i++){
    //generate dropdown list
    $('#ColSelect').append('<option>' + columns[i] + '</option>');
    //generate header
    $('#dataTable tr[class="theader"]').append('<td id="head_' + (i+1) +'"></td>');
    //generate table body
    $('#dataTable tr[class="tbody"]').append('<td name="col_' + (i+1) + '"></td>');
}
//JSON format data
var data = {
    'Column A': ['A1', 'A2', 'A3', 'A4', 'A5'],
    'Column B': ['B1', 'B2', 'B3', 'B4', 'B5'],
    'Column C': ['C1', 'C2', 'C3', 'C4', 'C5'],
    'Column D': ['D1', 'D2', 'D3', 'D4', 'D5'],
    'Column E': ['E1', 'E2', 'E3', 'E4', 'E5'],
    'Column F': ['F1', 'F2', 'F3', 'F4', 'F5'],
    'Column G': ['G1', 'G2', 'G3', 'G4', 'G5']
};
//Generate tr as per data size
for(var i=0; ++i < data['Column A'].length; ){
    $('#dataTable').append($('#dataTable tr:last').clone()); 
}
//after tr generate, add stripe style on tr
$("#dataTable tr:even[class!='theader']").css("background","#EFEFEF");
//register event on dropdown list.
var colIndex = 0;
$('#ColSelect').change(function(e){
    $("#ColSelect option:selected").each(function () {
        var val = $(this).val();
        if(val){
            colIndex++;
            $(this).remove();//remove selected from dropdown
            $('#head_'+colIndex).text(val).show();//css('display', 'block');//display header, Note:css('display', 'block') have compatibility issue on FF
            var idx = 0;
            $('td[name="col_'+colIndex+'"]').each(function(){
                $(this).text(data[val][idx++]).show();//loop to put value in each tr for one column
            });
        }
      });
});
    
});
</script>
<title>JQuery</title>
</head>
<body>
    <select id="ColSelect">
        <option value="">--Select--</option>
    </select>
    <table id="dataTable">
        <tr class="theader"></tr>
        <tr class="tbody"></tr>
    </table>
</body>
</html>