Alternative to .selector property now that it is removed in jQuery 1.9

北慕城南 提交于 2019-12-19 20:36:52

问题


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.



来源:https://stackoverflow.com/questions/14964760/alternative-to-selector-property-now-that-it-is-removed-in-jquery-1-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!