هل يمكنني الوصول إلى اسم عملية العبور الأخيرة المستخدمة في سلسلة؟

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

  •  04-10-2019
  •  | 
  •  

سؤال

كنت أتساءل عما إذا كان من الممكن الوصول إلى اسم الطريقة التي أنشأت مجموعة حالية من العناصر.

حاولت العثور عليه في كائن jQuery نفسه ، لكنني لا أرى مكانًا يمكن تخزينه فيه.

حاول ملء هذا

$.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'
هل كانت مفيدة؟

المحلول

هذا المثال ليس مثاليًا ، لكنه يستخرج العملية الأخيرة للعديد من المواقف (البحث ، مرشح ، أطفال ، التالي) - http://jsfiddle.net/x7lmw/3/ . استنادًا إلى الداخلية من 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;
    }
}

نصائح أخرى

يذهب المكافأة إلى bbonified لإيجاد الطريق.

هذه هي ترقيتي على وظيفة Last_Operation. تم التعرف على $ () على أنه .find () عن قصد.

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

تم استخدام هذا هنا: http://www.jsfiddle.net/naugtur/rdeau/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top