JQuery的每个功能?

时间:2012-09-06 08:11:41

标签: jquery

脚本:

var degress = GiveDegrees();

$(function () {
    //alert(GiveDegrees());  //output: 89,91,87,90,91
});

function GiveDegrees() {
    var divs = $('p.wx-temp');
    var degrees = new Array();

    $.each(divs, function (i, j) {
        degrees.push(stringToNum($(this).text()));
    });

    return degrees;
}

function stringToNum(str) {
    return str.match(/\d+/g);
}

我有这个:

$("p.wx-temp").each(degress, function (index) {
    $(this).append(degress[index], "<sup>°C</sup>");

    alert("I works");
});

但它不起作用。当我写这样的时候:

$("p.wx-temp").each(function (index) {
    $(this).append("<sup>°C</sup>");

    alert("I works");
});

有效。 .each()函数.each(data, function (index))没有重载方法吗?

degrees数组是整数数组,其中包含五个int 89,91,87,90,91。如何使用.each函数向每个p元素添加数组值。

感谢。

2 个答案:

答案 0 :(得分:3)

为什么需要将degress带入each?它已经可用,使用闭包:

$("p.wx-temp").each(function(index) {
    $(this).append(degrees[index], "<sup>°C</sup>");
    alert("I works");
});

OR

var $elems = $("p.wx-temp");
$.each(degrees, function(i, val) {
    $elems.eq(i).append(val, '<sup>°C</sup>');
});

如果元素长度与数组长度匹配,那么它应该与你循环的没有差别,但第一个可能更快(尽管使用本机数组循环会更快)。

请注意,您在两个部分中拼写degreesdegress的方式不同。

答案 1 :(得分:2)

var degrees = [89,91,87,90,91];
$("p.wx-temp").each( function (index) {
    $(this).append(degrees[index], "<sup>°C</sup>");

    alert("I work");
});