Jquery onclick prevent defaut behaviour

坚强是说给别人听的谎言 提交于 2020-01-06 02:51:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!