【问题标题】:simplify functions jquery简化函数 jquery
【发布时间】:2015-06-10 10:49:33
【问题描述】:

我有这些“功能”,这些“功能”在块中针对各种元素重复。 如何简化使用“var”?

谢谢你:)

例如:

$('#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 var light simplify


【解决方案1】:

为什么不直接创建一个函数,然后在函数内部调用该函数?

function active_here(this) {
      //code here..
}

【讨论】:

  • 在他调用它的那一刻,他在将方向作为参数的函数中。到那时,“这个”仍然是元素吗?我认为不是,但可能是错误的。
  • 是的,他可以在这里链接到具有相同问题的另一个线程-> stackoverflow.com/questions/7767593/…
  • 不确定我们是不是在说苹果对苹果。在该示例中,此人将“this”作为参数显式传递给回调函数。在这个问题中,他的函数需要一个“方向”的参数。
【解决方案2】:

Javascript 变量函数(也可以声明为普通函数):

var active_here = function($elem){
    $elem.addClass("here");
    $elem.prevAll().removeClass("here");
    $elem.prev().prev().addClass("here_pre");
    $elem.next().next().addClass("here_pre");
}

调用:

$('#test1').waypoint(function (direction) {
  if (direction === 'down') {
    active_here($(this));
  },
});

$('#test2').waypoint(function (direction) {
  if (direction === 'up') {
    active_here($(this));
  },
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多