如何使用apply()传递jQuery选择器?

时间:2015-07-06 22:57:24

标签: jquery

使用apply()通过使用选择器数组的[0]项将jQuery选择器转换为DOM元素。

我创建了一个调用函数来使用相同的上下文调用多个函数:

function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.apply(this, params); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg')); 

here's the jsFiddle

提前致谢。

1 个答案:

答案 0 :(得分:2)

apply方法需要一个数组作为第二个参数,所以这个:

func.apply(this, [params]);

应该按预期工作。或者您只需使用call()代替:

func.call(this, params);

function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.apply(this, [params]); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg'));	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="msg">Hello</div>

https://jsfiddle.net/doqm4sf5/4/

您想要使用call()吗?

function func1(){
    // do something with 'this'...
}

function func2(){
    // something else with 'this'...
}

function func3($msg){
    try{
        alert($msg.text());
    }catch(err){ alert(err); }
}

function invoke(context, funcs, params){
    funcs.forEach(function(func){ func.call(this, params); }.bind(context));
}

invoke(this, [func1, func2, func3], $('#msg'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="msg">Hello</div>