2012-04-25 49 views
1

我正在寫一個函數:jQuery的的onclick防止defaut行爲

(function($) { 
    $.fn.openBox = function(theId) { 
    // do something 
    }; 
})(jQuery); 

和幾個環節叫我的功能是這樣的:

<a href="#" onclick="$(this).openBox('#theBoxId');">Open the box !</a> 

我知道我可以防止回假默認行爲

<a href="#" onclick="$(this).openBox('#theBoxId'); return false">Open the box !</a> 

但是我希望把它在我的jQuery函數... 我和event.target測試,但它似乎並不工作...

回答

1

您可以return false;openBox插件內,並返回值在您的onclick屬性中;

(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')之類的操作。

什麼你應該做的是安裝一個事件the jQuery way,捕捉the event object並呼籲preventDefault()

jQuery.fn.openBox = function (id) { 
    return this.on('click', function (e) { 
     e.preventDefault(); 

     // now open your box `id`. 
    }); 
} 

$('a').openBox('#theBoxId'); 
0

相反的元素使用onclick的,把選擇的數據屬性:

<a href="#" data-openbox="#theBoxId">Open the box !</a> 

然後爲包含該數據的所有鏈接綁定點擊事件:

$(function(){ 
    $('a[data-openbox]').click(function(e){ 
    e.preventDefault(); 
    var selector = $(this).data('openbox'); 
    // do something 
    }); 
}); 

演示:http://jsfiddle.net/Guffa/EjLsQ/

+0

感謝Guffa! 數據屬性正常工作! – user1355748 2012-04-25 09:59:59