我可以在jQuery事件中包装javascript事件吗?

Cro*_*ros 10 javascript jquery

我有这个代码:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $('a.one').click(function(event){
                event.preventDefault();
            });
        });
        function test(event){
            event.preventDefault();
        }
    </script>
    <style type="text/css">
        a.test { font-weight: bold; }
        body { font-family:sans-serif; background-color:#AAAAAA;}
    </style>
</head>
<body>
    <a class="one" href="http://jquery.com/">jQuery</a>
    <br/>
    <a class="two" href="http://stackoverflow.com/" onclick='test(event)'>stack overflow</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

测试函数现在不起作用,因为常规javascript事件不支持jQuery事件preventDefault-function.有没有办法在jQuery事件中包装常规javascript事件,以便我可以使用例如preventDefault?

Dar*_*rov 12

试试这个:

function test(e) {
    $.Event(e).preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

事件对象

  • 这确实允许您访问某些方法,但不是"正常"的JQuery事件...例如,您不能使用:$ .Event(e).which (3认同)

Ian*_*son 5

我发现在jQuery事件中包装本机事件的最佳方法是fix:

event = $.event.fix(event);
Run Code Online (Sandbox Code Playgroud)

请注意,此功能不是公共API的一部分(尽管它应该是).