4

我想知道是否有可能获得创建当前元素数组的方法的名称。

我试图在 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'
4

2 回答 2

1

这个例子并不完美,但它提取了许多情况下的最后一个操作(查找、过滤、子级、下一个) - 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;
    }
}
于 2010-09-21T23:31:37.447 回答
0

赏金去 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/

于 2010-09-28T09:13:47.137 回答