我希望我能写出这样的东西
$("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/