开发者

Can I wrap a javascript event in a jQuery event?

I开发者_JS百科 have this code:

<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>

The test-function does not work as it stands now, since a regular javascript event doesn't support the jQuery event preventDefault-function. Is there some way to wrap a regular javascript event in a jQuery event so that I can use e.g. preventDefault?


Try this:

function test(e) {
    $.Event(e).preventDefault();
}

Event object


I've found the best way to wrap a native event in a jQuery event is with fix:

event = $.event.fix(event);

Please note, this function is not part of the public API (although it really should be).


I think it may be the fact that you're passing event in with onclick='test(event)'. I think onclick='test' is enough. I could be wrong though.


Yes (see Darin's answer). You could also work around IE's lack of preventDefault instead (which is essentially what jQuery is doing):

if ('preventDefault' in event)
    e.preventDefault();
else
    e.returnValue= false;


When you just want to execute the javascript - and not redirect - when clicking the href use "return false" in your click function. For example:

$(function(){
        $('a.one').click(function(event){
                var condition = confirm('Do you want to redirect to ...?');
                return condition == true;
        });
});

If you never want the link to redirect use 'javascript:void(0);' as href attribute, all browsers will still render it as a link instead of an anchor (some IE version do this).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜