需要查询只能构造一次

时间:2015-02-05 05:29:32

标签: javascript jquery

我有一个使用.slidetoggle来折叠2个段落的函数,并创建一个div来"展开"。代码工作正常但我正在尝试将其优化到我不需要每次构建查询的地方。有什么建议吗?

    <script type="text/javascript">
    $(document).ready(function(){

        $(".press_release").each(function(){
            if($(this).children("p").length > 1){
                $('<div><a href="#readmore" class="readmore">Read More&hellip;</a></div>').appendTo($(this));

                $(this).children("p").first().addClass('first-p');
                $(this).children("p").not('.first-p').hide();

                $(this).find('.readmore').click(function(){
                    $(this).parent().siblings('p').not('.first-p').slideToggle(500);
                    return false;
                });
            }

        });
    });
</script>

2 个答案:

答案 0 :(得分:2)

我会缓存$(this)引用,以避免一遍又一遍地重新创建jquery对象:

$(".press_release").each(function(){
       var myThis = $(this); 
       if(myThis.children("p").length > 1){
  ....

在整个脚本中使用缓存的引用。

答案 1 :(得分:0)

正如TGH所提到的,你应该缓存任何重复的查询。在您的代码中,我们关注三个主要查询:个人新闻稿($(this)),第一段和其他段落。

$(document).ready(function(){

  $(".press_release").each(function(){
    var $this = $(this),
      $paragraphs = $this.children("p"),
      $firstParagraph = $paragraphs.first();

    // Remove the first paragraph from our set
    $paragraphs = $paragraphs.not($firstParagraph);

    // We're only counting paragraphs after the first
    if($paragraphs.length > 0){
      $('<div><a href="#readmore" class="readmore">Read More&hellip;</a></div>').appendTo($this);

      $firstParagraph.addClass('first-p');
      $paragraphs.hide();

      // Delay the lookup of .readmore now; gain a slight benefit here at the
      // expense of a tiny cost each time something inside $this is clicked.
      // Binding directly to the .readmore element as you've done in your
      // original code likely won't have any noticeable impact either way.
      $this.on('click', '.readmore', function (){
        $paragraphs.slideToggle(500);
        return false;
      });
    }

  });
});