.click函数在没有参数的情况下工作,但不使用参数 [英] .click function working without arguments, but not working with arguments
问题描述
我有这个功能正常工作:
I have this function which was working:
$('#buttFurniture').click(onFilterCLick);
然后我决定在函数中添加一些参数并停止工作:
but then i decided to add some argument to the function and it stopped working:
$('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture));
全功能:
function onFilterCLick(arrFull,arrCurrent) {
$('#buttFurniture').css("background-color", "#F1F1F1");
$('#buttCars').css("background-color", "#F1F1F1");
$('#buttGames').css("background-color", "#F1F1F1");
$('#buttFurniture').css("color", "black");
$('#buttCars').css("color", "black");
$('#buttGames').css("color", "black");
$(this).css("background-color", "#656565");
$(this).css("color", "white");
if (jQuery.inArray(arrCurrent[0], arrFull)) {
console.log("asdasd");
}
}
推荐答案
解决方案:使用bind在传递函数时分配参数:
The solution: Use bind to assign arguments when passing functions:
$('#buttFurniture').click(onFilterCLick.bind($('#buttFurniture'), arrOutput, arrFurniture));
说明:在javascript中,函数就是所谓的第一类对象 - 这意味着它们可以作为变量传递,如其他基元(数字,布尔等),也可以作为函数的参数。
Explanation: In javascript, functions are what's known as first class objects - that means they can be passed around as variables, like other primitives (numbers, booleans etc.), but also as arguments to functions.
在这方面,重要的是要注意将函数作为变量传递和调用函数的关键区别。例如,考虑以下函数:
In this regard, it's important to note a key difference in passing a function as a variable, and invoking a function. For example, consider the following function:
var myFunc = function () {
return 0;
}
现在,请注意这两个陈述之间的区别:
Now, note the difference between these two statements:
typeof myFunc // "function"
typeof myFunc() // "number"
如您所见,第一个是对函数本身的引用,第二个是对函数的调用 - 一个微妙但关键的区别。
As you can see, the first is a reference to the function itself, and the second is the invocation of that function - a subtle but key difference.
您的点击处理程序需要函数作为其参数,而不是函数调用(或函数的结果是所谓的)。这就是为什么你必须使用bind:bind允许你传递函数本身,但也让你能够预先填充你传递的函数的参数。
Your click handler expects a function as it's argument, and NOT a function invocation (or the result of a function being called). That's why you must use bind: bind allows you to pass the function itself, but also gives you the ability to pre-fill the arguments of the function you're passing.
简而言之, bind()
函数(在您的情况下)需要3个参数 - 第一个参数,在每个中bind()
function,是这个
参数 - 设置这个
到你选择的元素是必要的,以便您的 $(this)
调用具有正确的上下文。其他参数是你预先填充函数其余参数的地方。
In brief, the bind()
function (in your case) takes 3 arguments - the first argument, in every bind()
function, is the this
parameter - setting this
to your selected element is necessary, so that your $(this)
invocation has the right context. The other arguments are where you pre-fill the rest of your function's parameters.
希望这会有所帮助!
这篇关于.click函数在没有参数的情况下工作,但不使用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!