[英].click function working without arguments, but not working with arguments
我有这个功能正在工作:
$('#buttFurniture').click(onFilterCLick);
但后来我决定在函数中添加一些参数并停止工作:
$('#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在传递函数时分配参数:
$('#buttFurniture').click(onFilterCLick.bind($('#buttFurniture'), arrOutput, arrFurniture));
说明:在javascript中,函数是所谓的第一类对象 - 这意味着它们可以作为变量传递,如其他基元(数字,布尔等),也可以作为函数的参数 。
在这方面,重要的是要注意将函数作为变量传递和调用函数的关键区别。 例如,请考虑以下功能:
var myFunc = function () {
return 0;
}
现在,请注意这两个陈述之间的区别:
typeof myFunc // "function"
typeof myFunc() // "number"
正如您所看到的,第一个是对函数本身的引用,第二个是对该函数的调用 - 一个微妙但关键的区别。
您的单击处理程序需要一个函数作为它的参数,而不是函数调用 (或函数的结果被调用)。 这就是为什么你必须使用bind:bind允许你传递函数本身 ,但也让你能够预先填充你传递的函数的参数。
简而言之, bind()
函数(在您的情况下)需要3个参数 - 每个bind()
函数中的第一个参数是this
参数 - this
设置为您选择的元素是必要的,以便您的$(this)
调用有正确的背景。 其他参数是预先填充函数其余参数的位置。
希望这可以帮助!
您可以使用click事件的回调函数来调用带参数的另一个函数。
$('#buttFurniture').click(function () {
onFilterCLick(arrOutput, arrFurniture)
});
当你不在函数定义中使用$(this)
时.bind(null,func_arguments)
我建议使用@JonathanBrooks描述的.bind(null,func_arguments)
方法,因为this
会引用window
对象。
但是,如果你想选择上下文为'this',那么我建议你这样使用:
function onFilterCLick(elem,arrFull,arrCurrent) {
//now you can use elem to refer $(this)
elem.css("background-color", "#656565");
}
并使用匿名函数进行click事件,如下所示:
$('#buttFurniture').click(function(){
onFilterCLick($(this),arrOutput,arrFurniture);
});
这里有一个工作代码示例
它不起作用,因为你在$('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture));
调用了onFilterCLick(arrOutput, arrFurniture)
$('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture));
不传递onFilterCLick
作为click事件的处理程序。
如果在DOM准备好后生成#buttFurniture
function onFilterCLick(arrOutput, arrFurniture) {
console.log(arguments);
console.log($(this));
$(this).toggleClass('red-border');
};
$('#buttFurniture').on('click', function (evt) {
evt.preventDefault();
var holder = onFilterCLick.bind(this);
holder('argOne', 'argTwo');
});
如果要选择单击的相同元素, .bind(this)
将覆盖this
内部函数范围。
我已经更新了这个例子,抱歉未经测试的代码,这里是fidle也读了这篇文章以获得更好的绑定理解;)
这也行。
var holder = onFilterCLick.bind(this, 'argOne', 'argTwo');
holder();
我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.