Function 简化函数jquery
我有这些“函数”,它们在块中为各种元素重复。 如何简化“var”的使用 谢谢:) 例如:Function 简化函数jquery,function,var,light,simplify,Function,Var,Light,Simplify,我有这些“函数”,它们在块中为各种元素重复。 如何简化“var”的使用 谢谢:) 例如: $('#test1').waypoint(function (direction) { if (direction === 'down') { $(this).addClass("here"); $(this).prevAll().removeClass("here"); $(this).prev().prev().addClass("here_pre"); $(this
$('#test1').waypoint(function (direction) {
if (direction === 'down') {
$(this).addClass("here");
$(this).prevAll().removeClass("here");
$(this).prev().prev().addClass("here_pre");
$(this).next().next().addClass("here_pre");
},
});
我想得出这样的解决方案:
var active_here = $(this).addClass("here"),
$(this).prevAll().removeClass("here"),
$(this).prev().prev().addClass("here_pre"),
$(this).next().next().addClass("here_pre");
最后回想一下这样的事情:
$('#test1').waypoint(function (direction) {
if (direction === 'down') {
active_here;
},
});
$('#test2').waypoint(function (direction) {
if (direction === 'up') {
active_here;
},
});
etc... etc... etc...
为什么不做一个函数,然后在函数内部调用函数呢
function active_here(this) {
//code here..
}
Javascript变量函数(也可以声明为普通函数): 电话:
$('#test1').waypoint(function (direction) {
if (direction === 'down') {
active_here($(this));
},
});
$('#test2').waypoint(function (direction) {
if (direction === 'up') {
active_here($(this));
},
});
你是在问如何编写自己的函数吗?在他调用函数的时候,他正在使用一个以方向为参数的函数。到那时,“这”仍然是元素吗?我认为不是,但可能是错的。是的,他可以。这里有一个链接到另一个线程,有相同的问题->不确定我们是否在谈论苹果对苹果。在该示例中,person显式地将“this”作为参数传递给回调函数。在这个问题中,他的函数需要一个“方向”参数。
$('#test1').waypoint(function (direction) {
if (direction === 'down') {
active_here($(this));
},
});
$('#test2').waypoint(function (direction) {
if (direction === 'up') {
active_here($(this));
},
});