jquery如果这个或这个

时间:2014-07-31 10:56:46

标签: jquery if-statement

下面我发布了一个脚本。它在我编辑第7行之前工作正常。我想隐藏某个div,屏幕的宽度是一定的大小,或者某个列表项的数量是1。

jQuery(document).ready(function($) {
    var $window = $(window);
    var $projectWidth = $('.project-images ul').width();
    var $projectLengh = $(".project-images ul li").length();
    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize > $projectWidth || $projectLengh == 1) {
            $('.controls').hide();
        }
    }
    checkWidth();   
    $(window).resize(checkWidth);
});

这是我的HTML& PHP。这是一个wordpress项目。

<div class="project-images-wrapper">
    <div class="project-images">
        <ul class="clearfix">

        <?php if( get_field('project_image_1') ): ?>
        <li><img src="<?php the_field('project_image_1'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_2') ): ?>
        <li><img src="<?php the_field('project_image_2'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_3') ): ?>
        <li><img src="<?php the_field('project_image_3'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_4') ): ?>
        <li><img src="<?php the_field('project_image_4'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_5') ): ?>
        <li><img src="<?php the_field('project_image_1'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_5') ): ?>
        <li><img src="<?php the_field('project_image_2'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_6') ): ?>
        <li><img src="<?php the_field('project_image_6'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_7') ): ?>
        <li><img src="<?php the_field('project_image_7'); ?>" /></li>
        <?php endif; ?>

          <?php if( get_field('project_image_8') ): ?>
        <li><img src="<?php the_field('project_image_8'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_9') ): ?>
        <li><img src="<?php the_field('project_image_9'); ?>" /></li>
        <?php endif; ?>

        <?php if( get_field('project_image_10') ): ?>
        <li><img src="<?php the_field('project_image_10'); ?>" /></li>
        <?php endif; ?>
        </ul>
    </div>
    <div class="controls">
    <button class="prev"></button>
    <button class="next"></button>
    </div>
</div>

1 个答案:

答案 0 :(得分:4)

错误使用长度。正如评论中所述,oGeez对其进行了更正,您必须使用.length而不是.length()。您的代码也可以通过以下方式进行改进:

jQuery(document).ready(function($) {
    // Check on document ready
    checkWidth();

    // Check on window resize event
    $(window).resize(checkWidth);
});

// Function to hide if conditions are valid
function checkWidth() {
    if ($(window).width() > $('.project-images ul').width() || $(".project-images ul li").length == 1) {
        $('.controls').hide();
    }
}