javascript 事件委托,jq,js模拟事件

时间:2022-12-01 18:50:25
<!DOCTYPE>
<html>
<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
</head>
<body>
    <ul id="myLinks">
        <li id="one">b</li>
        <li id="two">c</li>
        <li id="three">d</li>
    </ul>
    <script type="text/javascript">
        $(function () {
            var myLinks = $("#myLinks");
            myLinks.click(function (event) {
                var e = event ? event : window.event;
                var target = e.target || e.srcElement;
                switch (target.id) {
                    case "one":
                        alert("我是li id=>one点击触发");
                        break;
                    case "two":
                        alert("我是li id=>two点击触发");
                        break;
                    case "three":
                        alert("我是li id=>three点击触发");
                        break;
                    case "myLinks":
                        if (e.hasOwnProperty("originalEvent") == false) {
                            alert("jq模拟事件,同时我采用了事件委托(事件冒泡绑定事件)");
                        } else {
                            alert("javascript 模拟事件,同时我采用了事件委托(事件冒泡绑定事件)");
                        }
                        break;
                }
            });

            myLinks.trigger("click"); //jq模拟事件

            var oBtn = document.getElementById("myLinks");
            if (document.all) {
                oBtn.click();
            } else if (document.createEvent) {
                var obj = { type: "click" },
                    triggerEvent = document.createEvent("MouseEvents");
                "".fncreateEvent(obj, oBtn, triggerEvent);
            }
        });

        String.prototype.fncreateEvent = function (obj, btn, event) {
            obj = $.extend({
                type: obj.type,
                bubles: true,
                cancelable: true,
                view: document.defaultView,
                detail: 0,
                screenX: 0,
                screenY: 0,
                clientX: 0,
                clientY: 0,
                ctrlKey: false,
                altKey: false,
                shiftKey: false,
                metaKey: false,
                buttion: 0,
                relatedTarget: null
            }, obj);
            event.initMouseEvent(obj.type, obj.bubles, obj.cancelable, obj.view, obj.detail, obj.screenX, obj.screenY, obj.clientX, obj.clientY, obj.ctrlKey, obj.altKey, obj.shiftKey, obj.metaKey, obj.buttion, obj.relatedTarget);
            btn.dispatchEvent(event);
        }
    </script>
</body>
</html>