I was wondering if anyone knew why jQuery doesn't have a simple $().id()
method. It seems silly to have to pull the id using $().att开发者_JAVA百科r('id')
. I would think that the id attribute was common and useful enough to have its own call.
Why clutter up the namespace with superflous functions? You already said attr()
can do the same thing in only a few extra characters. For every extra function, it adds bytes to the file size, and time to the JavaScript parser.
Another problem is the jQuery returns a matched set, so typically you could have more than one id. By implementing an Id function, you could be breaking chainability by returning the id of the first item in a set.
You could simply use $('selector').get(0).id;
I think that if you really want and need that functionality to save time, I would just add it as a new method. Something along the lines of:
$.fn.extend({
id: function(){return this.attr('id');}
});
$('.test').id();
But I will echo the same concern that James Westgate said, if you have multiple returns in the collection, you need to make sure that you handle it properly or else you could break stuff.
精彩评论