javascript学习(一) 异常处理与简单的事件

一:异常处理

  

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form>
    <input id="txt" type="text" />
    <input id="btn" type="button" value="提交" onclick="demo2()" />
    </form>
    <script type="text/javascript">
        //系统错误
        function demo() {
            try {
                alert(str);
            }
            catch (err) {
                alert(err);
            }
        }
        //自定义错误
        function demo2() {
            //这里如果不写try ..catch..    throw ("text不能为空");  是不会弹出来的
            try {
                var e = document.getElementById("txt").value;
                if (e == "") {
                    throw ("text不能为空");
                }
            }
            catch (err) {
                alert(err);
            }
        }
    </script>
</body>
</html>

二:事件处理:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .div
        {
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="div" onmouseover="onOver(this)" onmouseout="onOut(this)">
    </div>
    <form>
    <input id="txt" type="text" onchange="onChange(this)" />
    <input id="txt2" type="text" onselect="onSelect(this)"   onfocus="onFocus(this)"/>
    </form>
    <script type="text/javascript">
        function onOver(e) {
            e.innerHTML = "Hello";
        }
        function onOut(e) {
            e.innerHTML = "World";
        }

        function onChange(e) { 
            alert("内容改变为:" +  e.value)
        }
        function onSelect(e) {
            e.style.color = "red";
        }
        function onFocus(e) {
            e.style.color = "black";
        }
    </script>
</body>
</html>

 效果:

1:当鼠标不再div上时

2:当鼠标放在div上时

3:修改txt的值为李鹏时:

4:选中一下tex2的值时:结果变为:

5:焦点放在tex2上时:结果为:

原文地址:https://www.cnblogs.com/lipeng0824/p/4414328.html