如何以文本形式获取 jQuery 选择器的表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/500246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:14:21  来源:igfitidea点击:

How do I get a jQuery selector's expression as text?

jqueryjquery-selectors

提问by Simon_Weaver

I have a jQuery selector, which has a chained function.

我有一个 jQuery 选择器,它有一个链式函数。

Inside the function I want to get access to the TEXT representing the expression for the selector.

在函数内部,我想访问表示选择器表达式的 TEXT。

$("cat dog").function() {

    // how do I get access to the "cat dog" string from inside THIS function ?
};

I've over simplified in this code sample what I actually want to do. I'm writing a plug-in and I need access to the selector for which the wrapped set has been created. Obviously in this particular example I have access to "cat dog" becasue i wrote it. So just picture this being in a plugin.

我在此代码示例中过度简化了我真正想做的事情。我正在编写一个插件,我需要访问已为其创建包装集的选择器。显然在这个特定的例子中,我可以访问“cat dog”,因为我写了它。所以想象一下这是在一个插件中。

Its a little tricky to google for this.

谷歌为此有点棘手。

edit:the 'selector' property is unfortunately now deprecated. http://jquery.com/upgrade-guide/1.9/#selector-property-on-jquery-objects

编辑:不幸的是,“选择器”属性现在已弃用。http://jquery.com/upgrade-guide/1.9/#selector-property-on-jquery-objects

采纳答案by Ryan Doherty

There is a 'selector' attribute in the jQuery object, but I'm not sure it's always available.

jQuery 对象中有一个“选择器”属性,但我不确定它是否始终可用。

回答by Pim Jager

This is far from optimal but works in some cases. You could do the following:

这远非最佳,但在某些情况下有效。您可以执行以下操作:

jQuery.fn._init = jQuery.fn.init
jQuery.fn.init = function( selector, context ) {
    return (typeof selector === 'string') ? jQuery.fn._init(selector, context).data('selector', selector) : jQuery.fn._init( selector, context );
};

jQuery.fn.getSelector = function() {
    return jQuery(this).data('selector');
};

This will return the last selector used for the element. But it will not work on non existing elements.

这将返回用于元素的最后一个选择器。但它不适用于不存在的元素。

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $('#foo').getSelector(); //'#foo'
 $('div[id="foo"]').getSelector(); //'div[id="foo"]'
 $('#iDoNotExist').getSelector(); // undefined
</script>

This works with jQuery 1.2.6 and 1.3.1 and possibly other versions.

这适用于 jQuery 1.2.6 和 1.3.1 以及可能的其他版本。

Also:

还:

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $foo = $('div#foo');
 $('#foo').getSelector(); //'#foo'
 $foo.getSelector(); //'#foo' instead of 'div#foo'
</script>

Edit
If you check immidiatly after the selector has been used you could use the following in your plugin:

编辑
如果您在使用选择器后立即检查,您可以在插件中使用以下内容:

jQuery.getLastSelector = function() {
    return jQuery.getLastSelector.lastSelector;
};
jQuery.fn._init = jQuery.fn.init
jQuery.fn.init = function( selector, context ) {
    if(typeof selector === 'string') {
        jQuery.getLastSelector.lastSelector = selector;
    }
    return jQuery.fn._init( selector, context );
};

Then the following would work:

那么以下将起作用:

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $('div#foo');
 $.getLastSelector(); //'#foo'
 $('#iDoNotExist');
 $.getLastSelector(); // #iDoNotExist'
</script>

In your plugin you could do:

在您的插件中,您可以执行以下操作:

jQuery.fn.myPlugin = function(){
 selector = $.getLastSelector;
 alert(selector);
 this.each( function() {
  //do plugins stuff
 }
}

$('div').myPlugin(); //alerts 'div'
$('#iDoNotExist').myPlugin(); //alerts '#iDoNotExist'

But still:

但仍然:

$div = $('div');
$('foo');
$div.myPlugin(); //alerts 'foo'

回答by Luca Matteis

If you're using firebug you could console.log(this)inside the function and see if the selector string is accessible somewhere in the object. Sorry I am not familiar with the jQuery API.

如果您使用的是萤火虫,您可以console.log(this)在函数内部查看选择器字符串是否可以在对象中的某处访问。抱歉,我不熟悉 jQuery API。

回答by Zeeshan

This will work if you want to access selector string in your function:

如果您想访问函数中的选择器字符串,这将起作用:

$(this).html();

This will also work if multiple selector are use,

如果使用多个选择器,这也将起作用,

for instance,

例如,

$('#id1,#id2').click(function(){
   alert($(this).html());
});

回答by Bruno Lesieur

Maybe this solve your problem :

也许这可以解决您的问题:

var $jqueryItems = $( ".my-selector" );
console.log( $jqueryItems.selector ); // display ".my-selector"

回答by curveball

For those who want to get inside their plugins selector string given to jQuery, I am glad to have improved the great answer given by @Pim Jager:

对于那些想要进入给 jQuery 的插件选择器字符串的人,我很高兴改进了@Pim Jager 给出的很好的答案:

  1. As of now (latest version 3.2.1) there are 3 arguments in jQuery.fn.initfunction - selector, context, root- not two;
  2. newkeyword should be added to the return statement of jQuery.fn.init;
  3. Inside your plugin the selectors are returned as a string by calling $(this).getSelector();
  1. 截至目前(最新版本 3.2.1),jQuery.fn.init函数中有 3 个参数- selector, context, root- 不是两个;
  2. new关键字应该添加到返回语句中 jQuery.fn.init
  3. 在您的插件中,选择器通过调用作为字符串返回 $(this).getSelector();

Finally, that's what I've got to work for me like a charm:

最后,这就是我必须为我工作的魅力:

(function($, window, document, undefined) { 
    $.fn._init = $.fn.init
    $.fn.init = function( selector, context, root ) {
        return (typeof selector === 'string') ? new $.fn._init(selector, context, root).data('selector', selector) : new $.fn._init( selector, context, root );
    };
    $.fn.getSelector = function() {
        return $(this).data('selector');
    };
    $.fn.YOUR-PLUGIN = function() {
        var selector = $(this).getSelector(); // selectors string given to jQuery 
        // other code
    }
})(jQuery, window, document);

It works with jQuery versions as far as I am concerned (from 1.7.0 to 3.2.1).

就我而言,它适用于 jQuery 版本(从 1.7.0 到 3.2.1)。

PS. Works fine even with jQuery 1.2.3 available here on stackoverflow too. So, I guess, the following is ok for all jQuery versions if you want to get a jQuery selector's expression as text inside the plugin:

附注。即使使用 jQuery 1.2.3 在 stackoverflow 上也可以正常工作。因此,我想,如果您想将 jQuery 选择器的表达式作为插件内的文本,以下内容适用于所有 jQuery 版本:

// our plugin
(function($, window, document, undefined) { 
    $.fn._init = $.fn.init
    $.fn.init = function( selector, context, root ) {
        return (typeof selector === 'string') ? new $.fn._init(selector, context, root).data('selector', selector) : new $.fn._init( selector, context, root );
    };
    $.fn.getSelector = function() {
        return $(this).data('selector');
    };
    $.fn.coolPlugin = function() {
        var selector = $(this).getSelector(); 
        if(selector) console.log(selector); // outputs p #boldText
    }
})(jQuery, window, document);

// calling plugin
$(document).ready(function() {
    $("p #boldText").coolPlugin();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<p>some <b id="boldText">bold text</b></p>

回答by David Mosher

I couldn't figure out how to get the reference to the string value of the selector provided to inside $('value_i_want_here') when bound to a function; seems like a tough problem. However, if you prefer testing in IE[x] there's always Firebug Litewhich works really well utilizing console.log(var|val).

当绑定到函数时,我无法弄清楚如何获取对提供给 $('value_i_want_here') 内部的选择器的字符串值的引用;似乎是一个棘手的问题。但是,如果您更喜欢在 IE[x] 中进行测试,那么Firebug Lite总是可以很好地利用 console.log(var|val)。

回答by pedalpete

well, I'm still trying to figure out if you are trying to get the element name? or the id and/or class or all of it.

好吧,我仍在尝试弄清楚您是否正在尝试获取元素名称?或 id 和/或类或全部。

You can get element with this

你可以用这个获取元素

var element =$(this).get(0);
var id = $(this).attr('id');
var class=$(this).attr('class');

not sure what happens if you have more than one class. might go into an array or something, and you could get that with the indexes.

不知道如果你有多个班级会发生什么。可能会进入一个数组或其他东西,你可以通过索引得到它。