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

时间:2011-03-29 18:46:31

标签: javascript 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 += '<li rel=""><span>'+thisOpts[thisSelected].text+'</span><ul>'
        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 += '<li rel="' + thisOpts[index].value + '"><span>' + thisOpts[index].text + '</span></li>'
            }
        }
        options_clone += '</ul></li>';

        var mySelect = $('<ul class="' + settings.myClass + '">').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;
}

4 个答案:

答案 0 :(得分:16)

  

只是一个单挑:.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();

答案 1 :(得分:5)

此页面讨论了获取选择器:

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

答案 2 :(得分:1)

这就是我在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版本。

答案 3 :(得分:1)

由于jQuery&#39; .selector的弃用和删除,我尝试了javascript&#39; 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);
    // e.g: .example   #example

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

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

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