2018/09/26

js使用例子


[TOC]

编码规范

html: https://github.com/fex-team/styleguide/blob/master/html.md
css: https://github.com/fex-team/styleguide/blob/master/css.md
javascript: https://github.com/fex-team/styleguide/blob/master/javascript.md


例子

JS打字机效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS打字机效果</title>
</head>
<body>
    <div id = "main"></div>
</body>
<script type = "text/javascript">
    var writerObj = {
        // 打字机内容
        msg: '',

        // 内容长度
        len: function(){
            return this.msg.length;
        },

        // 运行到第几个字
        seq: 0,

        //打字速度
        speed: 300,

        // 运行
        run: function(){
            var _this = this;
            document.getElementById("main").innerHTML = '&nbsp;'+_this.msg.substring(0, _this.seq);
            if (_this.seq == _this.len()) {
                _this.seq = 0;
            } else {
                _this.seq++;
            }
            var t = setTimeout(function(){_this.run()}, this.speed);
        }
    }
    window.onload = function(){
        writerObj.msg = "JS打字机效果......";
        writerObj.run();
    }
</script>
</html>

联动效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS联动效果</title>
</head>
<body>
    <select id="first">
    </select>

    <select id="second">
    </select>
</body>
<script>
    var t1 = [
        {"name":"中国", "value":"1"},
        {"name":"美国", "value":"2"}
    ];
    /*定义成二维数组*/
    var t2 = [
        [
            {"name":"中国11", "value":"11"},
            {"name":"美国11", "value":"11"}
        ],
        [
            {"name":"中国22", "value":"22"},
            {"name":"美国22", "value":"22"}
        ]
    ];

    var first = document.getElementById("first");
    var second = document.getElementById("second");

    /*先输出第一个复选框*/
    first.innerHTML = "";
    for (var i = 0; i < t1.length; i++) {
        first.innerHTML += "<option value='" + t1[i].value + "'>" + t1[i].name + "</option>";
    }
    /*默认输出第一个对应的内容*/
    for (var i = 0; i < t2[0].length; i++) {
        second.innerHTML += "<option value='" + t2[0][i].value + "'>" + t2[0][i].name + "</option>";
    }
    /*定义onchange事件 根据index输出对应的内容*/
    first.onchange = function(){
        var index = this.selectedIndex;
        second.innerHTML = "";
        for (var i = 0; i < t2[index].length; i++){
            second.innerHTML += "<option value='" + t2[index][i].value + "'>" + t2[index][i].name + "</option>";
        }
    }
</script>
</html>

其他细节操作

判断一个对象是否为空

if (JSON.stringify(data) == "{}") {
    console.log('is empty');
}

判断一个数组是否为空

if (JSON.stringify(data) == "[]") {
    console.log('is empty');
}