问题
I'm writing a function :
(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>
I know I can prevent default behaviour with return false :
<a href="#" onclick="$(this).openBox('#theBoxId'); return false">Open the box !</a>
But I want to put it in my jQuery function... I've tested with event.target but it doesn't seems to work...
回答1:
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);
and then:
<a href="#" onclick="return $(this).openBox('#theBoxId');">Open the box !</a>
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.
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');
回答2:
Instead of using onclick
in the element, put the selector in a data attribute:
<a href="#" data-openbox="#theBoxId">Open the box !</a>
Then bind a click event for all links with that data:
$(function(){
$('a[data-openbox]').click(function(e){
e.preventDefault();
var selector = $(this).data('openbox');
// do something
});
});
Demo: http://jsfiddle.net/Guffa/EjLsQ/
来源:https://stackoverflow.com/questions/10312848/jquery-onclick-prevent-defaut-behaviour