2011-02-18 63 views
0

我创建了一个插件,根据隐藏字段创建一个基于隐藏字段的复选框图像。我想重写is()函数...这可能吗?我基本上使用图像来模拟复选框。如何覆盖我的插件的jQuery全局函数?

HTML:

<input type="hidden" value="1" id="box" /> 

创建隐藏字段插件:

$('#box').myCheckbox(); 

我想能够做到以下几点:

$('#box').is(':checked'); 

是否有可能覆盖我的插件中的is()函数?

回答

2

没错:)

  (function() { 
       var proxied = jQuery.fn.is; 
       jQuery.fn.is= function() { 
       //do your things here 
       return proxied.apply(this, arguments);//call the default is here 
       }; 
      })(); 

顺便说一句:checked已经默认支持

所以如果u有

$( '#复选框')是( ':检查');//返回true/false取决于如果勾选复选框不要过于复杂的事情,因为你会拉你的头发出来后,当你忘了你做了这压倒一切的变化:)

+0

我没有完成我的问题。我没有提到我使用图像嘲笑复选框。 – 2011-02-18 10:46:30

+0

工程就像一个魅力! `var proxied = jQuery.fn.is; $ .fn.is = function(){ \t var t = $(this); (t.data('myCheckbox')!==未定义){ \t \t if(arguments。length === 1 && arguments [0] ===':checked'){ \t \t \t return t.data('myCheckbox')。getState()=== 1; \t \t} \t} \t return proxied.apply(this,arguments); };` – 2011-02-18 11:11:41

1

为什么你不能使用.attr('checked')

+0

因为我模拟一个“真正的”复选框(jQuery明智)。但我实际上在使用图像。 – 2011-02-18 10:42:51

3

您可以扩展jQuery的选择器并添加新的选择器。

http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/

例如:

$.extend($.expr[':'],{ 
    inline: function(a) { 
     return $(a).css('display') === 'inline'; 
    } 
}); 

这允许你做:

$(':inline'); // Selects ALL inline elements

$('a:inline'); // Selects ALL inline anchors

编辑:

在你的情况下,模仿的复选框,首先抓住从jQuery的代码:检查...这就是:

return elem.checked === true; 

然后

$.extend($.expr[':'],{ 
    checked: function(a) { 
     if(a.isMySpecialCheckbox()) return a.hasAPropertyThatSignifiesChecked; 
     else return elem.checked === true; 
    } 
}); 

尝试,我还没有尝试过,但它应该工作。