jQuery – 8.事件和事件参数

事件


(*)JQuery中的事件绑定:$(“#btn”).bind(“click”,function(){}),每次都这么调用太麻烦,所以jQuery可以用$(“#btn”).click(function(){})来进行简化。unbind

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Jqeury/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("input[value='bind']").click(function() {
                $("#btn").bind(
                    {
                        "click": function() { alert("click"); },
                        "mouseover": function() { alert("mouseover"); },
                        "mouseout": function() { alert("mouseout"); }
                    }
                );
            });
           
            
            $("input[value='unbind']").click(function () {
                //移除事件
                //$("#btn").unbind("mouseout");
                //移除所有事件
                $("#btn").unbind();
            })
            
        })
    </script>
</head>

<body>
    <input >
    <input type="button" value="bind">
    <input type="button" value="unbind">
    <input  type="button" value="one" />
</body>
</html>

一次性事件:如果绑定的事件只想执行一次随后立即unbind可以使用one()方法进行事件绑定

            //一次性事件
            $("input[value='one']").click(function () {
                $("#btn").one("click", function() {
                    alert("click");
                });
            })

(*)合成事件 hover ,hover(enterfn (焦点),leavefn (离开焦点)),当鼠标放在元素上时调用enterfn方法,当鼠标离开元素的时候调用leavefn方法。 (toggle() :jquery.1.9删除了切换功能)

mouseover、mouseenter的区别:div里套div。见备注。和事件冒泡有关系。

事件冒泡:JQuery中也像JavaScript一样是事件冒泡

如果想获得事件相关的信息,只要给响应的匿名函数增加一个参数:e,e就是事件对象。调用事件对象的stopPropagation()方法终止冒泡。e. stopPropagation();

$("tr").click(function(e) { alert("tr被点击"); e.stopPropagation(); });//注意函数的参数是e

阻止默认行为:有的元素有默认行为,比如超链接点击后会转向新链接、提交按钮默认会提交表单,如果想阻止默认行为只要调用事件对象的preventDefault()方法和Dom中的window.event.returnValue=false效果一样。

$("a").click(function(e) { alert("所有超链接暂时全部禁止点击"); e.preventDefault(); });