如何在jQuery中将数组传递给函数

6
我希望将一个数组传递给一个函数(你能告诉我这样做是否正确吗?),然后在函数中,我希望循环遍历数组中的值,并将每个值附加到以下HTML中的LI元素中。这是我目前的代码:用户将编写他想要传递的URL值。
var arrValues = ['http://imgur.com/gallery/L4CmrUt', 'http://imgur.com/gallery/VQEsGHz'];
calculate_image(arrValues);

function calculate_image(arrValues) {
    // Loop over each value in the array.
    var jList = $('.thumb').find('href');
    $.each(arrValues, function(intIndex, objValue) {
        // Create a new LI HTML element out of the
        // current value (in the iteration) and then
        // add this value to the list.
        jList.append($(+ objValue +));
    });
}
}

HTML

<li>
    <a class="thumb" href="" title="Title #13"><img src="" alt="Title #13" /></a>
    <div class="caption">
        <div class="download">
            <a href="">Download Original</a>
        </div>
        <div class="image-title">Title #13</div>
        <div class="image-desc">Description</div>
    </div>
</li>

全局变量已经可以被函数访问,为什么还需要将其传递进去呢? - Furqan Hameedi
1
jQuery 不等于 JavaScript。jQuery 只是一个库。 - John Dvorak
1
你的代码有问题还是只是想要进行代码审查? - Rory McCrossan
var jList = $('.thumb').find('href'); 试图查找 .thumb 元素内的所有 href 元素。看起来您正在尝试将多个参数(href)添加到单个 <a> 标签中。您需要为每个 URL 创建一个 <a> 元素。 - Rembunator
1个回答

8
如果您想传递一个数组,只需将它作为参数放入即可。 在Javascript中,您可以将数字、字符串、数组、对象甚至函数作为参数传递。
查看此示例以获取缩略图生成器实现:http://jsfiddle.net/turiyag/RxHys/9/ 首先,定义这些数组。
var bluearray = [
    'http://fc02.deviantart.net/fs30/f/2008/056/8/0/Purple_hair___Bipasha_Basu_by_mstrueblue.jpg',
    'http://static.becomegorgeous.com/img/arts/2010/Feb/20/1805/purple_hair_color.jpg',
    'http://img204.imageshack.us/img204/6916/celenapurpleqp7.jpg'
    ];
var greenarray = [
    'http://25.media.tumblr.com/tumblr_m7fqmkNEhc1qlfspwo1_400.jpg',
    'http://www.haircolorsideas.com/wp-content/uploads/2010/12/green-red-hair.jpg',
    'http://fc02.deviantart.net/fs71/i/2010/011/9/c/Neon_Yellow_and_Green_Hair_by_CandyAcidHair.jpg'
    ];

当DOM加载完成后,调用函数加载缩略图。

$(function() {
    addThumbs(bluearray);
    addThumbs2(greenarray);
});

addThumbs使用jQuery的each函数使代码更简洁。我发现它比普通的Javascript for循环更美观,也更易于使用。

function addThumbs(paths) {
    $.each(paths,function(index, value) {
        $("div").append('<img src="' + value + '" />');
    });
}

但如果你是原生JavaScript的粉丝,那么普通的for循环在addThumbs2中被实现。

function addThumbs2(paths) {
    for(index in paths) {
        $("div").append('<img src="' + paths[index] + '" />');
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接