我有一个页面对网络(来自 Alexa)排名前 15 位的网站进行评级,它使用 javascript 来编写新的评级,但这是非常低效的。每个等级有 6 个变量。它使用变量为每个评级编写一个代码块。有没有办法让它使用一个代码块来编写所有 15 个评级?这是一些代码:
var topID1 = 1;
var topWidth1 = 100;
var topPageURL1 = 'www.google.com'
var topPageTitle1 = 'Google';
var topRate1 = rateStar9;
var topMargin1 = 0;
$('#topSites1').html('<div class="meter-wrap" style="margin-top: ' + topMargin1 + 'px;"><div class="meter-value" style="background-color: ' + topSitesBack + '; width: ' + topWidth1 + '%;"><div class="meter-text"><span class="toplist"><span class="topnum">' + topID1 + '. </span><span class="favico" id="ico1"><img src="img/blank.gif" style="width:16px;height:16px;"></img></span><a href="http://' + topPageURL1 + '/">' + topPageTitle1 + '</a><span class="rating" style="width: ' + topRate1 + 'px;"><img src="img/blank.gif" style="width:100%;height:16px;"></img></span></span></div></div></div>');
$('#ico1').css('background', 'url(' + topPageFavicon + topPageURL1 + ') no-repeat');
(重复 15 次)
最佳答案
它使用 javascript 对象调用。比你可以迭代对象来获取信息:
var all_ratings = {
'GOOGLE': {
topID: 1,
topWidth: 100,
topPageURL: 'something',
topPageTitle: 'something_else',
topRate: rateStar,
topMargin: 'something'
},
'YAHOO': {
topID: 1,
topWidth: 100,
topPageURL: 'something',
topPageTitle: 'something_else',
topRate: rateStar,
topMargin: 'something'
},
..MORE
}
比你能做的(使用 $.each
):(因为我相信你正在使用 jQuery):
$.each(all_ratings, function (index, item)
{
var outerDiv = $('<div>', {
'class': 'meter-wrap',
style: 'margin-top: ' + item.topMargin + 'px;'
}),
innerDiv = $('<div class="meter-value" style="background-color: ' + topSitesBack + '; width: ' + item.topWidth + '%;">').html('<div class="meter-text"><span class="toplist"><span class="topnum">' + item.topID + '. </span><span class="favico" id="ico1"><img src="img/blank.gif" style="width:16px;height:16px;"></img></span><a href="http://' + item.topPageURL + '/">' + item.topPageTitle + '</a><span class="rating" style="width: ' + item.topRate + 'px;"><img src="img/blank.gif" style="width:100%;height:16px;"></img></span></span></div>');
innerDiv.appendTo(outerDiv);
$('#topSites').append(outerDiv);
})
fiddle :http://jsfiddle.net/maniator/QWAhV/
旁注:除了使用 topPageTitle
,您还可以使用 index
变量,它会返回您正在访问的页面,例如 ' GOOGLE' 或 'YAHOO',为此而摆弄:http://jsfiddle.net/maniator/QWAhV/8/
关于javascript - 获取一个脚本来循环遍历多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938164/