现在替换.selector属性,它在jQuery 1.9中被删除

时间:2013-02-19 18:28:12

标签: javascript jquery jquery-selectors deprecated jquery-1.9

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

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

我需要 .selector 的地方的一个示例是当我已经通过名称创建了一组复选框时,我希望在该组中看到哪一个是检查

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

  

来自文档:      .jQuery对象上的.selector属性

     

jQuery上不推荐使用的.selector属性的剩余用途   object是为了支持已弃用的.live()事件。在1.9,jQuery没有   因此,在链式方法中维护此属性的时间更长   .live()从不支持使用链式方法。不要   在jQuery对象上使用.selector属性。 jQuery Migrate   插件不会尝试维护此属性。

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

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

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