Подтвердить что ты не робот

Получение начального селектора внутри плагина 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;
}
4b9b3361

Ответ 1

Просто хедз-ап:.selector() устарела в jQuery 1.7 и удалена в jQuery 1.9: api.jquery.com/selector. - Саймон Стейнбергер

Используйте свойство .selector в коллекции jQuery.

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 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();

Ответ 3

То, как я получаю селекторные строки внутри моих плагинов в 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>

Ответ 4

Из-за устаревания и удаления 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);
    // e.g: .example   #example

Итак, теперь мы можем использовать это для любых целей. Вы можете использовать его как селектор jQuery... например. $($selector)

EDIT: Мой первоначальный ответ получит только атрибут, который сначала появляется в элементе. Поэтому, если мы хотим получить id, который был помещен после класса в элементе, это не сработает.

В моем новом решении используется объект для хранения информации об атрибутах, поэтому мы можем проверить, существуют ли оба или только один, и соответственно установить требуемый селектор. Благодаря решению ManRo для вдохновения.