jQuery:获取原始选择器

时间:2011-08-27 03:04:11

标签: javascript jquery selector

我正在编写插件,我希望能够获得jQuery用于创建对象的原始选择器。

因此,如果您想应用类似.siblings()的内容,您可以获得该类型的所有兄弟姐妹,无论是查找某个类的兄弟姐妹还是特定元素类型的兄弟姐妹。

  • jQuery('div') - 'div'
  • jQuery(jQuery('div')) - '[jQuery] object' // would require recursively finding the selector of this
  • jQuery('#elment') - '#element'
  • jQuery('.class') - '.class'

3 个答案:

答案 0 :(得分:11)

只需访问jQuery对象的selector属性:

console.log($("div").selector); // 'div'
console.log($("#foo").selector); // '#foo'

答案 1 :(得分:2)

作为卡里姆所做的扩展:

var t = jQuery('.clName');

t.each(function(){ 
   jQuery(this).data('selector',t.selector);
});

答案 2 :(得分:1)

这似乎可能更长了 ...在版本3中删除了“ .selector”,jquery建议两次将选择器传入。

https://api.jquery.com/selector/ ....

  

.selector属性在jQuery 1.7中已弃用,仅在jQuery Migrate插件中支持.live()所需的范围内进行维护。在将来的版本中,可能会删除它,恕不另行通知。 该属性从来都不是选择器的可靠指标,因为以后的遍历方法可能会更改该集合,所以该选择器不能用于获取当前包含在jQuery集合中的元素集。需要在其插件中使用选择器字符串的用户可以要求将其作为方法的参数。例如,一个“ foo”插件可以写为$ .fn.foo = function(选择器,选项){/ *插件代码在这里* /} ;,使用该插件的人会写$(“ div.bar “).foo(” div.bar“,{dog:” bark“}); 重复使用“ div.bar”选择器作为.foo()的第一个参数。