Posso accedere a un nome dell'ultima operazione di traslazione utilizzato in una catena?

StackOverflow https://stackoverflow.com/questions/3764794

  •  04-10-2019
  •  | 
  •  

Domanda

mi chiedevo se è possibile arrivare al nome del metodo che ha creato una serie di elementi corrente.

Ho cercato di trovare nell'oggetto jquery in sé, ma non vedo un posto dove potrebbe essere conservato.

Prova a riempire questo in

$.fn.myfunc=function(){
//your brilliant idea here
return functname;
}

$('body').find('.a').myfunc(); //returns 'find'
$('body').children('.a').myfunc(); //returns 'children'
$('body').find('.a').next('div').myfunc(); //returns 'next'

//and if You're really awesome:
    $('body').find('.a').next('div').css('float','left').myfunc(); //returns 'next'
È stato utile?

Soluzione

Questo esempio non è perfetto, ma estrae l'ultima operazione per molte situazioni (trovare, filtro, bambini, accanto) - http://jsfiddle.net/X7LmW/3/ . In base al largo delle parti interne del jQuery.pushStack http: // GitHub .com / jquery / jquery / blob / master / src / Core.js # L204

function last_operation( $$ ) {
    var selector = $$.selector,
        selector_cmpr;

    while ( ( selector_cmpr = remove_paren( selector ) ) != selector ) {
        selector = selector_cmpr;
    }

    var operations = selector.split('.'),
        is_find    = selector.replace(/, /, '').split(' ').length > 1,
        operation;

    if ( is_find ) {
        operation = 'find';
    } else if ( operations.length > 1 ) {
        operation = operations[ operations.length - 1 ].replace(/PAREN/, '')
    } else {
        operation = 'unknown';
    }
    return operation;

    function remove_paren( str ) {
        var str_cmpr = str.replace(/\([^()]+\)/, 'PAREN');
        return str_cmpr;
    }
}

Altri suggerimenti

Bounty va a BBonified per trovare la strada.

Questo è il mio aggiornamento sulla funzione last_operation. $ () è riconosciuto come .find () di proposito.

$.fn.lastop=function(){
var s=this.selector.replace(/^.*\.([a-zA-Z]+)\([^()]*\)[^ ()]*$|.*/,'$1');
return s?s:'find';
}

Questo è stato utilizzato qui: http://www.jsfiddle.net/naugtur/rdEAu/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top