未捕获的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/