未捕获的TypeError:undefined不是函数javascript函数 [英] Uncaught TypeError: undefined is not a function javascript function

查看:104
本文介绍了未捕获的TypeError:undefined不是函数javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了气泡排序"功能来对图像列表进行排序.我不明白为什么该函数返回"Uncaught TypeError:undefined不是一个函数". 谁能帮我吗?

I wrote the "bubble sort" function to sort a list of images. I can't understand why the function returns the "Uncaught TypeError: undefined is not a function". Can anyone help me?

$j(document).ready(function() { 
    var list = $j("dt").find("a").find("img");

    bubbleSort(list, list.size());    
});


function bubbleSort(a, size)
{
    do {
        var swapped = false;
        for (var i = 0; i < size - 1; i++) {
            var img = getAlt(a, i);
            var img2 = getAlt(a, i + 1);

            if (img > img2) {
                var temp = a[i].attr('src');
                a[i].attr('src') = a[i + 1].attr('src');
                a[i + 1].attr('src') = temp;
                swapped = true;
            }
        }
    } while (swapped); // <----- line error
}

function getAlt(list, pos) {
    var img = list[pos].attr("alt");
    img = img.split(' ');
    return img[3];
}

推荐答案

使用list.eq(pos)代替list[pos],因为第一个获取原始的HTML元素(不具有attr函数),第二种方式您将获得一个jQuery对象(具有attr函数)

Instead of list[pos] use list.eq(pos) since with the first one you get a raw HTML element (which has no attr function) and the second way you get a jQuery object (which has an attr function)

还使用list.length而不是list.size(),因为自版本1.8起不推荐使用size函数

Also use list.length instead of list.size() since the size function has been deprecated since version 1.8

最后由M. Page指出

Finally as noted by M. Page

a[i].attr('src') = a[i + 1].attr('src');

应该是

a.eq(i).attr('src', a.eq(i + 1).attr('src'));

类似的语句也是如此

如果img没有alt属性,您还应该考虑更改getAlt函数

You should also consider altering your getAlt function in the event that the img does not have an alt attribute

function getAlt(list, pos) {
    var img = list.eq(pos).attr("alt") || "";    
    if(img) {
        img = img.split(' ');
    }
    return img[3] || "";
}

所有这些更改都可以在以下小提琴中找到 http://jsfiddle.net/ejhq03qy/1/

All of these changes can be found in the following fiddle http://jsfiddle.net/ejhq03qy/1/

这篇关于未捕获的TypeError:undefined不是函数javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆