javascript 同位素JS错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31049168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:10:35  来源:igfitidea点击:

Isotope JS Error

javascriptjquery

提问by user2202463

Need a bit of help with a Js error I am getting please:

需要一些帮助来解决我收到的 Js 错误:

Uncaught TypeError: $portfolio.isotope is not a function

未捕获的类型错误:$portfolio.isotope 不是函数

  
//ISOTOPE FUNCTION - FILTER PORTFOLIO FUNCTION

    $portfolio = $('.portfolio-items');
    $portfolio.isotope({
        itemSelector : 'li',
        layoutMode : 'fitRows'
    });
    $portfolio_selectors = $('.portfolio-filter >li>a');
    $portfolio_selectors.on('click', function(){
        $portfolio_selectors.removeClass('active');
        $(this).addClass('active');
        var selector = $(this).attr('data-filter');
        $portfolio.isotope({ filter: selector });
        return false;
    });

回答by Turnip

If you don't want your script to run on pages that don't contain the required elements (.portfolio-items), you can run your script conditionally based on the lengthproperty of your element collection stored in $portfolio:

如果您不希望您的脚本在不包含所需元素 ( .portfolio-items) 的页面上运行,您可以根据length存储在 中的元素集合的属性有条件地运行您的脚本$portfolio

$portfolio = $('.portfolio-items');

if ($portfolio.length) { // if 'length' is non zero. Enter block...

    $portfolio.isotope({
        itemSelector : 'li',
        layoutMode : 'fitRows'
    });
    $portfolio_selectors = $('.portfolio-filter >li>a');
    $portfolio_selectors.on('click', function(){
        $portfolio_selectors.removeClass('active');
        $(this).addClass('active');
        var selector = $(this).attr('data-filter');
        $portfolio.isotope({ filter: selector });
        return false;
    });

}