2012-09-06 40 views
0

腳本: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))是否沒有過載方法?

度數組是包含五個int的整數數組,如89,91,87,90,91。如何使用.each函數將數組值添加到每個p元素。

謝謝。

+0

'{89,91,87,90,91}'是不是有效的對象。 –

+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的方式不同。

+0

這就是我的想法:http://jsfiddle.net/dApgU/ –

+0

這是解決方案。謝謝它仍然不適用於我:((我認爲還有另一個問題,當我用alert alert [0 ]出它的每個功能。 –

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

    alert("I work"); 
});