开发者

jQuery custom selection

I'd like to extend jQuery selection so that it treats a given selection value as an ID.

For example, when you do $("foo.bar") , jQuery will try to select all elements with the tag name foo and the class bar, but I want jQuery to select the element with an ID of foo.bar. Instead of having to escape开发者_开发知识库 dots and prepend a # each time, I'd like to add to jQuery as a function so that I can do something like $("id:foo.bar").

Is this possible with jQuery? If so, can anyone show me some examples?

Thanks.


It is. You can create you own selectors by extending .expr[]. Example:

$.extend($.expr[':'], {
   'id': function(elem, i, attr){   
      return( elem.id === attr[3] );
   }
});

Usage would be:

$(':id(foo.bar)');

Demo: http://www.jsfiddle.net/cwwGk/1/


If you replace ID selection with an attribute filter, it will have to test every element on the page for that ID instead of using document.getElementById.

If you want a little more convenience, just create your own wrapper. you can use jQuery's namespace if you want:

jQuery.byId = function(id){return $(document.getElementById(id));};

$.byId('foo.bar').addClass('something');


you can do $("[id=foo.bar]")


I don't have specific code to do this. Be aware that overriding the global behavior of jquery may break plugins that others have made. If you can you should use the 'sub' feature of jquery 1.5. It is designed specifically to 'sub'stitute jquery features while retaining the default functionality for other plugins.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜