Alternative to .selector property now that it is r

2020-04-08 12:04发布

问题:

As of jQuery 1.9 the .selector property of jQuery objects has been removed. (I'm a little confused as to why, exactly). I actually use it in a few unique scenarios, and I know that I could do other things to prevent this. Just wondering if anyone knows another way of grabbing the selector as of 1.9?

$('#whatever').selector // (would of returned '#whatever')  

One example of where I need .selector is when I already have a group of checkboxes by name, and I want to see, within that group, which one is checked:

jsFiddle DEMO

var $test = $('input[name="test"]');

console.log( $test );
console.log( $(':checked', $test).attr('id') ); // returns --undefined--

console.log( 'now with .selector: ');
console.log( $($test.selector + ':checked').attr('id') ); // returns correct

From the docs: .selector property on jQuery objects

The remaining purpose of the deprecated .selector property on a jQuery object is to support the deprecated .live() event. In 1.9, jQuery no longer attempts to maintain this property in chained methods, since the use of chained methods was never supported with .live(). Do not use the .selector property on a jQuery object. The jQuery Migrate plugin does not attempt to maintain this property.

回答1:

There should not be many reasons to actually need the original selector. In your specific use case, if you want to narrow down the set of selected elements, you can use .filter [docs]:

$test.filter(':checked').attr('id')

$('#whatever').selector still seems to work though. The documentation says "In 1.9, jQuery no longer attempts to maintain this property in chained methods [...]". Though http://api.jquery.com/selector claims it was removed in 1.9. I don't know, it's a bit confusing.