[英]Can I wrap a javascript event in a jQuery event?
I 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. 测试函数现在不能正常工作,因为常规的javascript事件不支持jQuery事件preventDefault-function。 Is there some way to wrap a regular javascript event in a jQuery event so that I can use eg preventDefault?
有没有办法在jQuery事件中包装常规javascript事件,以便我可以使用例如preventDefault?
I've found the best way to wrap a native event in a jQuery event is with fix
: 我发现在jQuery事件中包装本机事件的最佳方法是使用
fix
:
event = $.event.fix(event);
Please note, this function is not part of the public API (although it really should be). 请注意,此功能不是公共API的一部分(尽管它应该是)。
I think it may be the fact that you're passing event in with onclick='test(event)'. 我认为可能是你用onclick ='test(event)'传递事件。 I think onclick='test' is enough.
我认为onclick ='test'就足够了。 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):
您也可以解决IE缺少preventDefault(这实际上是jQuery正在做的事情):
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. 当你只想执行javascript - 而不是重定向 - 当你点击href时,在你的点击功能中使用“return false”。 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);' 如果您从未希望链接重定向,请使用'javascript:void(0);' as href attribute, all browsers will still render it as a link instead of an anchor (some IE version do this).
作为href属性,所有浏览器仍将它呈现为链接而不是锚(某些IE版本执行此操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.