在 jQuery 中获取准确的选择器/替代 .selector

Get exact selector in jQuery / alternative to .selector

我希望我能写出这样的东西

$("div.banana .for aside.scale").yellowify();

$.fn.yellowify = function () {
    this.css("color","yellow");
    alert($(this).selector);
});

哪个会提醒

div.banana .for aside.scale

这个问题与 this one 非常相似,但是发帖者想通过扫描选择器的父级或类似的东西来检索 DOM 结构。我只想要选择器 原样 ,没有任何额外的 类 或 ID。我想要它完全,因为它在第一行。

jQuery 曾经有这个 .selector 属性,但它已在 1.7 中弃用并在 1.9 中删除(or has it? - thanks Ted. UPDATE .selector will only be removed in jQuery 3.0!). The docs 状态:

Plugins that need to use a selector string within their plugin can require it as a parameter of the method. For example, a "foo" plugin could be written as $.fn.foo = function( selector, options ) { /* plugin code goes here */ };, and the person using the plugin would write $( "div.bar" ).foo( "div.bar", {dog: "bark"} ); with the "div.bar" selector repeated as the first argument of .foo().

但我认为那非常丑陋,而且根本不友好。是否有一种不需要用户采取任何行动的替代方案? IE。不需要任何额外的参数?


对于那些好奇的人,理想情况下我希望我的插件能够为特定元素回显样式,就像这样,但显然要复杂得多:

$.fn.yellowify = function () {
    var css = $(this).selector + "{color: yellow;}";
    // I can add rules for specific elements now as well
    css += $(this).selector + " .child {color: red;}";
    $("<style>").html(css).appendTo("head");
});

连同参数,这让我的插件可以发挥更大的作用。

在您的示例中,您的用例是静态插件示例,而不是原型插件示例。使用 $.fn.myPlugin 你要求你的插件的用户操作它,因为它是 jQuery API 的一部分。在这种情况下,插件设计为在调用链 ($(this).each()) 的那个点迭代 jQuery 对象。

但是你的例子看起来像它作用于实际的 jQuery 对象本身而不是选定的元素并且最好作为 jQuery [=24= 上的插件]对象:

$.yellowify = function (selector) {
  var css = selector + "{color: yellow;}";
  // I can add rules for specific elements now as well
  css += selector + " .child {color: red;}";
  $("<style>").html(css).appendTo("head");
});

目前还不完全清楚您为什么想要这样做。奇怪的是外星人。但是,对于作用于 jQuery 原型链的完整性插件,需要遍历已经选择的元素和 return 原始集合。如果您需要在选择范围内查找元素,那么您可以使用 .find().