获取原始选择器

jQuery: Get original selector

本文关键字:选择器 原始 获取      更新时间:2023-09-26

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

如果你想应用像.siblings()这样的东西你可以得到该类型的所有兄弟元素,无论是查找某个类的兄弟元素还是某个元素类型的兄弟元素

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

直接访问jQuery对象的selector属性:

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

这似乎不再可能了…'.选择器'在版本3中被删除,而jquery建议传递两次选择器。

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

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

作为Karim所放内容的扩展:

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