在jquery插件中获取初始选择器

我之前得到了一些关于选择器的帮助,但我坚持以下。

假设你有一个这样的插件

$('#box').customplugin(); 

如何在插件中将#box作为字符串? 不确定这是否是正确的做法,任何其他解决方案也会很棒。

考虑#box是一个选择下拉列表,

我遇到的问题是如果我做常规的JavaScript

 $('#box').val(x); 

选择了正确的选项值,

但如果我在插件中尝试相同的内容

 ..... this.each(function() { var $this = $(this); $this.val(x); 

最后一个代码并没有真正做任何事情。

我注意到我在插件中定位#box有困难,因为它是一个对象,而不是一个字符串……

任何帮助,将不胜感激。

谢谢!

编辑::放入我正在努力的代码以便更好地理解

 (function($){ $.fn.customSelect = function(options) { var defaults = { myClass : 'mySelect' }; var settings = $.extend({}, defaults, options); this.each(function() { // Var var $this = $(this); var thisOpts = $('option',$this); var thisSelected = $this[0].selectedIndex; var options_clone = ''; $this.hide(); options_clone += '
  • '+thisOpts[thisSelected].text+'
      ' for (var index in thisOpts) { //Check to see if option has any text, and that the value is not undefined if(thisOpts[index].text && thisOpts[index].value != undefined) { options_clone += '
    • ' + thisOpts[index].text + '
    • ' } } options_clone += '
  • '; var mySelect = $('
      ').html(options_clone); //Insert Clone Options into Container UL $this.after(mySelect); //Insert Clone after Original var selectWidth = $this.next('ul').find('ul').outerWidth(); //Get width of dropdown before hiding $this.next('ul').find('ul').hide(); //Hide dropdown portion $this.next('ul').css('width',selectWidth); //on click, show dropdown $this.next('ul').find('span').first().click(function(){ $this.next('ul').find('ul').toggle(); }); //on click, change top value, select hidden form, close dropdown $this.next('ul').find('ul span').click(function(){ $(this).closest('ul').children().removeClass('selected'); $(this).parent().addClass("selected"); selection = $(this).parent().attr('rel'); selectedText = $(this).text(); $(this).closest('ul').prev().html(selectedText); $this.val(selection); //This is what i can't get to work $(this).closest('ul').hide(); }); }); // returns the jQuery object to allow for chainability. return this; }

    **编辑**克雷格打败我** /编辑**

    **编辑**只是一个单挑:.selector()在jQuery 1.7中被弃用,并在jQuery 1.9中删除: api.jquery.com/selector 。 – Simon Steinberger ** /编辑**

    在jQuery集合上使用.selector属性。

     var x = $( "#box" ); alert( x.selector ); // #box 

    在你的插件中:

     $.fn.somePlugin = function() { alert( this.selector ); // alerts current selector (#box ) var $this = $( this ); // will be undefined since it's a new jQuery collection // that has not been queried from the DOM. // In other words, the new jQuery object does not copy .selector alert( $this.selector ); } 

    然而,以下可能解决了您真正的问题?

     $.fn.customPlugin = function() { // .val() already performs an .each internally, most jQuery methods do. // replace x with real value. this.val(x); } $("#box").customPlugin(); 

    这个页面讨论了获取选择器:

    http://api.jquery.com/selector/

    这就是我在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(); }); 
      

    some bold text

    由于jQuery的.selector的弃用和删除,我已经尝试了javascript的DOM Nodes并提出了2017年及以后的解决方案,直到更好的方式出现…

     //** Get selector **// // Set empty variables to work with var attributes = {}, // Empty object $selector = ""; // Empty selector // If exists... if(this.length) { // Get each node attribute of the selector (class or id) $.each(this[0].attributes, function(index, attr) { // Set the attributes in the empty object // In the form of name:value attributes[attr.name] = attr.value; }); } // If both class and id exists in object if (attributes.class && attributes.id){ // Set the selector to the id value to avoid issues with multiple classes $selector = "#" + attributes.id } // If class exists in object else if (attributes.class){ // Set the selector to the class value $selector = "." + attributes.class } // If id exists in object else if (attributes.id){ // Set the selector to the id value $selector = "#" + attributes.id } // Output // console.log($selector); // eg: .example #example 

    所以现在我们可以将它用于任何目的。 您可以将它用作jQuery选择器…例如。 $($selector)

    编辑:我的原始答案只会获得首先出现在元素上的属性。 因此,如果我们想要获取在元素上的类之后放置的id ,它将无法工作。

    我的新解决方案使用一个对象来存储属性信息,因此我们可以检查是否存在两个或仅存在一个,并相应地设置所需的选择器。 感谢ManRo的灵感解决方案 。