天天看点

标签和js对象绑定事件以及传参问题

总结:

(1)在标签οnclick=”“中写的js代码会自动嵌套在function(){};

(2)js中绑定事件并传参数主要是通过function(){setName(name);}将代码要绑定的函数在其中调用,并在外层定义好参数;

代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>标签和js对象绑定事件以及传参问题</title>
        <script src="js/jquery-3.2.1.js"></script>
    </head>
    <body>
        (1)在标签onclick=""中写的js代码会自动嵌套在function(){}<br/>
        (2)js中绑定事件并传参数主要是通过function(){setName(name);}将代码要绑定的函数在其中调用,并在外层定义好参数;<br/>
        <input type="button" name="button" value="标签绑定事件错误事例" onclick="function(){alert('dfd');}"/><br/>
        <label>绑定事件错误事例,这样不会调用这个函数</label><br/>
        <input type="button" name="button" value="标签绑定事件" onclick="alert('标签绑定事件');"/><br/>
        <input type="button" id="jsbutton" name="jsbutton" value="原生js绑定事件"/><br/>
        <input type="button" name="jquerybutton" value="jquery绑定事件"/><br/>
        <input type="button" name="jquerybuttonParmErr" value="jquery绑定事件错误传参"/><br/>
        <input type="button" name="jquerybuttonParm" value="jquery绑定事件传参"/><br/>
    </body>
    <script>
        function setName(name) {
            alert("name");
        }
        $("input[name='jquerybutton']").click(function(){
            alert("jquery绑定事件");
        });
        var name = "绑定事件传参";
        /*
         * 原生js绑定事件并传参数
         */
        var jsbutton = window.document.getElementById("jsbutton");
        jsbutton.onclick = setName(name);//错误绑定,这样并没有绑定点击事件而是直接运行

        jsbutton.onclick = function() {
            setName(name);
        }
        /*
         * jquery绑定事件并传参数:
         * 通过jQuery为事件处理函数传入的参数Event对象,
         * 我们可以获取当前事件的相关信息(比如事件类型、触发事件的DOM元素、附加数据等)
         */
        $("input[name='jquerybuttonParmErr']").click(function(event){
            console.log(event);//代表当前事件对象
            console.log(this);//代表触发事件的对象
        });

        $("input[name='jquerybuttonParm']").click(function(){
            alert(name);
        });
        $("input[name='jquerybuttonParm']").click(function(){
            setName(name);
        });
    </script>
</html>
           

继续阅读