这远非最佳,但在某些情况下有效。您可以执行以下操作:
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');
};
这将返回用于元素的最后一个选择器。但它不适用于不存在的元素。
<div id='foo'>Select me!</div>
<script type='text/javascript'>
$('#foo').getSelector(); //'#foo'
$('div[id="foo"]').getSelector(); //'div[id="foo"]'
$('#iDoNotExist').getSelector(); // undefined
</script>
这适用于 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>
编辑
如果您在使用选择器后立即检查,您可以在插件中使用以下内容:
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 );
};
然后以下将起作用:
<div id='foo'>Select me!</div>
<script type='text/javascript'>
$('div#foo');
$.getLastSelector(); //'#foo'
$('#iDoNotExist');
$.getLastSelector(); // #iDoNotExist'
</script>
在您的插件中,您可以执行以下操作:
jQuery.fn.myPlugin = function(){
selector = $.getLastSelector;
alert(selector);
this.each( function() {
//do plugins stuff
}
}
$('div').myPlugin(); //alerts 'div'
$('#iDoNotExist').myPlugin(); //alerts '#iDoNotExist'
但仍然:
$div = $('div');
$('foo');
$div.myPlugin(); //alerts 'foo'