How do I get a jQuery selector's expression as text?
I have a jQuery selector, which has a chained function.
Inside the function I want to get access to the TEXT representing the expression for the selector.
$("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.
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
jQuery对象中有一个'selector'属性,但我不确定它始终可用。
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.
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'
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.