未捕获TypeError:无法调用未定义的方法'split'

问题描述:

我想在我的网站上包含流沙脚本,但是我失败了。
萤火虫给我这个错误:65 Uncaught TypeError: Cannot call method 'split' of undefined
未捕获TypeError:无法调用未定义的方法'split'

这个脚本:

jQuery.noConflict(); 
jQuery(document).ready(function($){ 
    // Clone applications to get a second collection 
    var $data = $("#portfolio-items").clone(); 

    //NOTE: Only filter on the main portfolio page, not on the subcategory pages 
    $('#portfolio-terms ul li').click(function(e) { 
     $("ul li").removeClass("active"); 
     // Use the last category class as the category to filter by. This means that multiple categories are not supported (yet) 
     var filterClass=$(this).attr('class').split(' ').slice(-1)[0]; 
jquery.custom.js:65 Uncaught TypeError: Cannot call method 'split' of undefined (repeated 6 times) 

     if (filterClass == '.all current') { 
      var $filteredData = $data.find('#portfolio-'); 
     } else { 
      var $filteredData = $data.find('#portfolio-[data-type=' + filterClass + ']'); 
     } 
     $("#portfolio-items").quicksand($filteredData, { 
      duration: 800, 
      easing: 'swing', 
     });  
     $(this).addClass("active");    
     return false; 
    }); 
}); 


在这里看到:http://stakk.it/
什么错误?

谢谢你,对不起我的英文不好!

+0

你为什么会认为filterClass可能可能等于'。所有current'? – Neil

如果.attr("class")回报undefined,你不能称之为.split它,因为.splitString对象的方法,不能在undefined调用。您需要存储.attr("class")的结果,然后只在不是undefined时将其拆分。

var filterClass = $(this).attr('class'); 
filterClass = filterClass ? filterClass.split(' ').slice(-1)[0] : ''; 

现在filterClass将包含您期望的内容或空字符串。

编辑:你可以用this.className代替$(this).attr('class'),从已删除的答案中拉出。

+0

非常感谢您的回答。现在我解决了这个问题,但我不明白为什么图像会消失。你可以在这里看到它:http://stakk.it/ – humanbeing

另一种解决方案是使用toString方法

var filterClass = $(this).attr('class').toString(); 
    filterClass = filterClass.split(' '); 

它为我工作