2011-10-07 69 views
0

内选择我创建了一个插件,像怎么知道的jQuery插件

jQuery.fn.Foo = function() { 

      //var str= get selector some_how ; alert(str);  

      //at this point get selector that invoked this function 


      //eg: 
      /* 
       jQuery('.red').Foo(); /// alert's .red 
       jQuery('#something_else') //alert's #something_else 
      */ 


    } 
+0

可能的重复:http://stackoverflow.com/questions/4680498/jquery-object-selector-as-string –

回答

2

jQuery的对象有一个选择属性。您可以访问this.selector

0

这就是我如何得到选择的字符串我的插件内,2017年:

(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/2.1.1/jquery.min.js"></script> 
 
<p>some <b id="boldText">bold text</b></p>

的想法是有条件包基础上选择字符串是否提供或不提供jQuery的init()功能。如果提供了,请使用jQuery的data()方法将选择器字符串与最终调用的原始init()相关联。小getSelector()插件只需要预先存储的值。它可以稍后在您的插件中调用。它应该适用于所有jQuery版本。