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

我试图在我的网站上加入Quicksand脚本,但我失败了。
Firebug给了我这个错误: 65 Uncaught TypeError: Cannot call method 'split' of undefined

对于这个脚本:

 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/
什么是错误?

谢谢你,抱歉我的英文不好!

如果.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') ,从已删除的答案中取出。

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

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

它对我有用