【问题标题】:Uncaught TypeError: Cannot call method 'split' of undefined未捕获的类型错误:无法调用未定义的方法“拆分”
【发布时间】:2011-12-20 16:45:26
【问题描述】:

我试图在我的网站上包含流沙脚本,但我失败了。
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/
错误是什么?

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

【问题讨论】:

  • 您为什么认为 filterClass 可能等于 .all current

标签: jquery


【解决方案1】:

如果.attr("class") 返回undefined,则不能在其上调用.split,因为.splitString 对象的方法,不能在undefined 上调用。您需要存储.attr("class") 的结果,然后仅在不是undefined 时才拆分它。

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

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

编辑:您可以将 $(this).attr('class') 替换为 this.className,从已删除的答案中提取。

【讨论】:

  • 非常感谢您的回答。现在我解决了这个问题,但我不明白为什么图像消失了。你可以在这里看到它:stakk.it
【解决方案2】:

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

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

它对我有用

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 2013-08-31
    • 2011-11-12
    • 2013-09-14
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多