简体   繁体   English

如何使此jquery代码减少冗余并提高效率?

[英]How do I make this jquery code less redundant and more efficient?

I'm relatively new to writing javascript. 我是写JavaScript的新手。 The js code below is modified from a previous answer I found on here. 下面的js代码是根据我在这里找到的先前答案修改而成的。 It does exactly what I want it to do functionality-wise, however, it's redundant and calling the code every time the mouse enters (which takes more resources than it needs too). 它正是按照我希望它在功能上的用途来完成的,但是,它是多余的,并且每次鼠标进入时都会调用代码(这会占用更多的资源,而这也需要)。

Any suggestions on how to make this less redundant and more efficient? 关于如何减少冗余和提高效率的任何建议?

SIMPLIFIED DEMO HERE: http://jsfiddle.net/nsnzd9cL/ 简化的演示在这里: http : //jsfiddle.net/nsnzd9cL/

HTML: HTML:

<div class="container">
    <div class="category" id="commercials">
        <p>Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />
        </p>
        <div class="scroll">
            <p>Scroll</p>
        </div>
    </div>
    <div class="category" id="photography">
        <p>Something
            <br />Something
            <br />
        </p>
        <div class="scroll">
            <p>Scroll</p>
        </div>
    </div>
    <div class="category" id="experiments">
        <p>Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />Something
            <br />
        </p>
        <div class="scroll">
            <p>Scroll</p>
        </div>
    </div>
</div>

JS: JS:

  var arrow1 = $('#commercials .scroll');
var arrow2 = $('#photography .scroll');
var arrow3 = $('#experiments .scroll');

$("#commercials").mouseenter(function () {

    if ($('#commercials').hasScrollBar()) {
        arrow1.css({
            'visibility': 'visible'
        });
    } else {
        arrow1.css({
            'visibility': 'hidden'
        });
    }
});

$("#photography").mouseenter(function () {

    if ($('#photography').hasScrollBar()) {
        arrow2.css({
            'visibility': 'visible'
        });
    } else {
        arrow2.css({
            'visibility': 'hidden'
        });
    }
});

$("#experiments").mouseenter(function () {

    if ($('#experiments').hasScrollBar()) {
        arrow3.css({
            'visibility': 'visible'
        });
    } else {
        arrow3.css({
            'visibility': 'hidden'
        });
    }
});

(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > (this.height() + 1);
    }
})(jQuery);

JSFiddle 的jsfiddle

Bind the event to the container and apply it to the elements within the container, in this case the specified IDs. 将事件绑定到容器,并将其应用于容器中的元素(在本例中为指定的ID)。 Then look up elements relative to the target when triggered: 然后在触发时查找相对于目标的元素:

$('.container').on('mouseenter','#commercials,#photography,#experiments', function(){
    var $this   = $(this),
        $scroll = $this.find('.scroll');

    if( $this.hasScrollBar() ){
        $scroll.css('visibility','visible');
    } else {
        $scroll.css('visibility','hidden');
    }   
});

(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > (this.height() + 1);
    }
})(jQuery);

but really, I'd replace the '#commercials,#photography,#experiments' with '.category' ; 但实际上,我会用'.category'替换'#commercials,#photography,#experiments' '.category' ; JSFiddle using .category . JSFiddle使用.category

Using .category gives you the added benefit of adding new categories dynamically and not having to rebind events when they're created after the page load, since the event is still on the container. 使用.category为您带来额外的好处,即动态添加新类别,并且在页面加载后创建事件时不必重新绑定事件,因为事件仍在容器中。

I have reduce all the redundancy I could find: 我减少了所有可能发现的冗余:

(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > (this.height() + 1);
    }

    var $commercials = $( "#commercials" ),
        $photography = $( "#photography" ),
        $experiments = $( "#experiments" );

    var mouseEnterListner = function() {
        var arrow = $(this).find( '.scroll' );

        if ( $(this).hasScrollBar() ) {
            arrow.css({
                'visibility': 'visible'
            });
        } else {
            arrow.css({
                'visibility': 'hidden'
            });
        };
    };

    $commercials.on('mouseenter', function() {
        mouseEnterListner.call(this);
    });

    $photography.on('mouseenter', function() {
        mouseEnterListner.call(this);
    });

    $experiments.on('mouseenter', function() {
        mouseEnterListner.call(this);
    });
})(jQuery);

Good luck, have fun! 祝你好运,玩得开心!

This is how I would do it... 这就是我要做的

JS Fiddle JS小提琴

$(document).ready(function(){
    scrollCheck();
});

function scrollCheck() {
    var div = '',
        scroll = true;
    $('.category').each(function( index ) {
        div = $(this);
        scroll = div.get(0).scrollHeight <= (div.height() + 1);
        console.log(scroll); // just a check
        if (scroll) {
            div.children('.scroll').remove();
        }
    });
}

Easy to read and non redundant code: 易于阅读且非冗余的代码:

var arrow1 = $('#commercials .scroll');
var arrow2 = $('#photography .scroll');
var arrow3 = $('#experiments .scroll');

function bindMouseEnter(id, arrow){

   $("#"+id).mouseenter(function () {

       if ($('#'+id).hasScrollBar()) {
          arrow.css({
            'visibility': 'visible'
          });
      } else {
        arrow.css({
            'visibility': 'hidden'
        });
      }
    });

}

bindMouseEnter('commercials', arrow1);
bindMouseEnter('photography', arrow2);
bindMouseEnter('experiments', arrow3);


(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > (this.height() + 1);
    }
})(jQuery);

Continueing from Vijay's answer, we can combine the selector: 从Vijay的答案继续,我们可以组合选择器:

(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > (this.height() + 1);
    }

    $("#commercials,#photography,#experiments").on('mouseenter', function() {
        var arrow = $(this).find('.scroll');

        if ( $(this).hasScrollBar() ) {
            arrow.css({
                'visibility': 'visible'
            });
        } else {
            arrow.css({
                'visibility': 'hidden'
            });
        };
    };
})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM