自定义函数

来源:互联网 发布:js vr 插件 互动 编辑:程序博客网 时间:2024/06/10 16:56
<!doctype html>
<html>
    <head>
        <title>自定义函数</title>
<!--
之前的Js代码都是一加载就运行, 但是很多时候我们不要一加载就运行, 而需要点击按钮, 链接, 图片才执行
需要有方法的概念: 怎么在JS里面创建方法(函数)

function 函数名(参数1, 参数2, ....){

}
调用:
事件 = 方法();
onclick

利用表单中的name属性来获取对应控件中的值:


-->
        <script type="text/javascript">
            function testFun (){
                alert("调用了testFun()方法");
            }
            function test (i, d){
                alert(i+" -- "+d);
            }
            function getSum (){
                var a = document.myForm.a.value;
                var b = document.myForm.b.value;
                var c = eval( a + "+" + b );
                document.myForm.c.value = c;
            }
            function getDiv (){
                var a = document.myForm.a.value;
                var b = document.myForm.b.value;
                var c = eval( a + "-" + b );
                document.myForm.c.value = c;
            }
        </script>
    </head>

    <body>
        <input type="button" value="  测 试  " onclick="testFun()" />

        <form name="myForm">
            第一个数字: <input type="text" name="a" /><br />
            第二个数字: <input type="text" name="b" /><br />
            <input type="button" value=" + " onclick="getSum()"/>&nbsp;&nbsp;
            <input type="button" value=" - " onclick="getDiv()"/>&nbsp;&nbsp;
            <input type="button" value=" * "/>&nbsp;&nbsp;
            <input type="button" value=" / "/>&nbsp;&nbsp;<br />
            结果:<input type="text" name="c" />
        </form>
    </body>
</html>

1 0