jquery - 在 jQuery 中获取精确选择器/替代 .selector

标签 jquery 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? - 感谢 Ted。更新 。选择器只会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");
});

与参数一起,这使我能够更深入地使用我的插件。

最佳答案

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

但是,您的示例看起来像是作用于实际的 jQuery 对象本身,而不是作用于选定的元素,并且最好用作 jQuery class 对象上的插件:

$.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 原型(prototype)链的插件需要循环已选择的元素并返回原始集合。如果您需要在选择范围内查找元素,那么您可以使用 .find() .

关于jquery - 在 jQuery 中获取精确选择器/替代 .selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490974/

相关文章:

用于查找链接和其中所有元素的 jQuery 选择器

jquery - 为 IE6 实现 + 选择器

php - 使用 Ajax 提交表单时更改消息的颜色

javascript - 基于类的按钮单击事件不会在动态创建的按钮上触发。

javascript - 如何让这个表单在提交时做两件事(AJAX 和 PHP 邮件)?

javascript - 如何使用 JavaScript 检测系统是否安装了网络摄像头插件?

swift - Action 的多个参数/参数 - Swift

objective-c - 为什么 objc_msgSend 导致 EXC_BAD_ACCESS?

javascript - 通过更改 Selector 重用代码

javascript - 在angularjs中突出显示跨度的文本