在这种情况下需要“功能”吗?

时间:2014-02-20 15:26:33

标签: javascript jquery css

有没有办法整理这个剧本?

$( ".switchViewHide" ).click(function() {
  $( ".topTitles h2" ).fadeOut( "slow", function(){});
  $(".topControls h3").fadeOut("slow"), function(){};
  $(".topControls h3").fadeOut("slow"), function(){};
  $("#videoControls p").fadeOut("slow"), function(){};
  $("#pageControls div.switchViewHide").fadeOut("slow"), function(){};
  $("#pageControls div.switchViewShow").fadeIn("slow"), function(){};
  $("#countdownBar").fadeOut("slow"), function(){};
  $("#grid").fadeOut("slow"), function(){};
});

我尝试删除“功能”,因为它已空,但它不再有效。

  • 基本上单击按钮,所有这些元素都会消失(淡出 出)。
  • 加上一个元素淡入(它是一个按钮替换)
  • 将使用CSS类(使用.addClass)

它看起来有点乱,是否有更简单的方法可以在一次点击中应用许多不同的东西?

1 个答案:

答案 0 :(得分:2)

您可以检查,该功能是可选的

$( ".switchViewHide" ).click(function() {
    $( ".topTitles h2" ).fadeOut("slow");
    $(".topControls h3").fadeOut("slow");
    // $(".topControls h3").fadeOut("slow"); // duplicate
    $("#videoControls p").fadeOut("slow");
    $("#pageControls div.switchViewHide").fadeOut("slow");
    $("#pageControls div.switchViewShow").fadeIn("slow");
    $("#countdownBar").fadeOut("slow");
    $("#grid").fadeOut("slow");
});

你可以通过使用类来简化这一过程,甚至可以在你想要它们时进行切换:

$( ".switchViewHide" ).click(function() {
    // These will work once
    $(".HideOnClick").fadeOut("slow");
    $(".ShowOnClick").fadein("slow");
});

$( ".switchViewHide" ).click(function() {
    // These will toggle every click, based on their start visibility
    $(".toggleVisibility").stop().fadeToggle("slow");
    // Note the `.stop()`, when you click really fast a couple of times, it will queue animation
    // stop will stop the current animation, and continue to the next one.
});

代码可以做得更好。当你有一个ID作为开始时,使用find()组合以获得更好的性能(jQuery使用javascript本身的快速getElementById()):

// not so good
$("#pageControls div.switchViewShow")
// better:
$("#pageControls").find("div.switchViewShow")

在第一行中,将在整个文档中查找所有div.switchViewShow,然后删除所有不在#pageControls中的人。 在第二行中,将查找所有div.switchViewShow,但仅限于#pageControls

好读(也适用于经验丰富的程序员!):
http://lprocksit.blogspot.nl/2012/05/jquery-advanced-performance-best.html
http://blog.sathomas.me/post/jquery-best-practices

相关问题