如何将jQuery选择器的表达式作为文本?

Sim*_*ver 31 jquery jquery-selectors

我有一个jQuery选择器,它具有链式功能.

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

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

    // how do I get access to the "cat dog" string from inside THIS function ?
};
Run Code Online (Sandbox Code Playgroud)

我在这个代码示例中简化了我实际想要做的事情.我正在编写一个插件,我需要访问已创建包装集的选择器.显然,在这个特殊的例子中,我可以访问"猫狗",因为我写了它.所以只是想象一下插件.

这对谷歌来说有点棘手.

编辑:遗憾的是,'selector'属性现已弃用.http://jquery.com/upgrade-guide/1.9/#selector-property-on-jquery-objects

Rya*_*rty 18

jQuery对象中有一个'selector'属性,但我不确定它是否始终可用.

  • 现已弃用:-( http://jquery.com/upgrade-guide/1.9/#selector-property-on-jquery-objects (4认同)

Pim*_*ger 8

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

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');
};
Run Code Online (Sandbox Code Playgroud)

这将返回用于元素的最后一个选择器.但它不适用于非现有元素.

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

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

也:

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

编辑
如果在使用选择器后进行了immidiatly检查,则可以在插件中使用以下内容:

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 );
};
Run Code Online (Sandbox Code Playgroud)

然后以下工作:

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

在你的插件中你可以做到:

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

$('div').myPlugin(); //alerts 'div'
$('#iDoNotExist').myPlugin(); //alerts '#iDoNotExist'
Run Code Online (Sandbox Code Playgroud)

但仍然:

$div = $('div');
$('foo');
$div.myPlugin(); //alerts 'foo'
Run Code Online (Sandbox Code Playgroud)