jQuery onclick防止违约行为 [英] Jquery onclick prevent defaut behaviour
问题描述
我正在写一个函数:
(function($) {
$.fn.openBox = function(theId) {
// do something
};
})(jQuery);
和几个调用我的函数的链接是这样的:
and several links calling my function like this :
<a href="#" onclick="$(this).openBox('#theBoxId');">Open the box !</a>
我知道我可以使用 return false 来阻止默认行为:
I know I can prevent default behaviour with return false :
<a href="#" onclick="$(this).openBox('#theBoxId'); return false">Open the box !</a>
但是我想把它放在我的jQuery函数中... 我已经对event.target进行了测试,但似乎无法正常工作...
But I want to put it in my jQuery function... I've tested with event.target but it doesn't seems to work...
推荐答案
您可以在openBox
插件中添加return false;
,并在onclick
属性中返回 that 的值;
You can return false;
inside your openBox
plugin, and return the value of that in your onclick
attribute;
(function($) {
$.fn.openBox = function(theId) {
return false;
};
})(jQuery);
然后:
<a href="#" onclick="return $(this).openBox('#theBoxId');">Open the box !</a>
但是,这与理想情况相差很远. jQuery应该是可链接的.但是通过返回false
而不是this
,您将无法再执行:$('foo').openBox().trigger('change')
等.
However, this is far from ideal. jQuery is expected to be chainable; but by returning false
rather than this
, you can no longer do: $('foo').openBox().trigger('change')
and the like.
您 应该做的是附加一个事件 jQuery方式 ,捕获事件对象并调用 preventDefault()
:
What you should be doing is attaching an event the jQuery way, capturing the event object and calling preventDefault()
:
jQuery.fn.openBox = function (id) {
return this.on('click', function (e) {
e.preventDefault();
// now open your box `id`.
});
}
$('a').openBox('#theBoxId');
这篇关于jQuery onclick防止违约行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!