在jQuery 1.9中删除了.selector属性后,它成为了该属性的替代项

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

本文关键字:属性 jQuery 删除 selector      更新时间:2023-09-26

自jQuery 1.9起,jQuery对象的.selector属性已被删除。(确切地说,我有点困惑)。事实上,我在一些独特的场景中使用它,我知道我可以做其他事情来防止这种情况只是想知道是否有人知道从1.9开始抓选择器的另一种方法

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

我需要.selector的一个例子是,当我已经有一组名称的复选框时,我想看看在该组中,哪个被选中

jsFiddle演示

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

从文档中:.jQuery对象上的选择器属性

jQuery上弃用的.selector属性的剩余用途对象用于支持弃用的.live()事件。在1.9中,jQuery没有尝试在链式方法中维护此属性的时间更长,因为.live()从未支持使用链式方法。请勿对jQuery对象使用.selector属性。jQuery迁移插件不会尝试维护此属性。

实际上需要原始选择器的原因应该不多。在您的特定用例中,如果您想缩小所选元素的范围,可以使用.filter[docs]:

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

$('#whatever').selector似乎仍然有效。文档中说"在1.9中,jQuery不再试图在链式方法[…]中维护此属性"http://api.jquery.com/selector声称它在1.9中被删除。我不知道,这有点令人困惑。

我只需要将选择器保存在这样的变量中:

var testSelector = 'input[name="test"]';
var test = $(testSelector);
console.log( $(testSelector + ':checked').attr('id') );

对于我正在处理的代码,我能够替换

if ($elem.selector == 'date-column-filter')){

带有

if ($elem.hasClass('date-column-filter')){