我正试图在下面的代码中添加一个计数器。
我正在迭代页面中的DOM元素,并将文本字符串转换为对象。我正在尝试创建以下原型的对象:
// my desired object layout:
eligList = {
'perfect': {
'id': 1,
'qty': 3
}
}
$(document).ready(function() {
eligList = {};
// FROM: http://www.jquery4u.com/jquery-functions/jquery-each-examples/
$(selector).each(function(index, value) {
$this = $(this); // cache
apr = parseFloat($.trim($this.find('.apr .js-apr').text()));
eligName = $.trim($this.find('.eligibility .js-hist').text());
eligList[eligName] = (eligList[eligName] || {});
switch(eligName) {
case 'perfect':
eligID = 1;
// THE PROBLEM!
console.log('eligList', eligList.perfect); // empty :s
eligList[eligName]['qty'] = (eligList[eligName]['qty']++ || 1); // eligList.perfect.qty never gets set (at all)
break;
case 'excellent':
eligID = 2;
break;
case 'good':
eligID = 3;
break;
case 'average':
eligID = 4;
break;
default:
eligID = 5;
break;
}
eligList[eligName] = {'id': eligID};
$this.data({'apr': apr, 'elig': eligID});
console.group('article ' + index);
console.log(apr);
console.log(eligID);
console.groupEnd();
});
console.log(eligList);
});
我怀疑这是范围问题。所以,我的问题是,如何让我的脚本计算perfect
、excellent
、good
等的quantity
?
这里有一个工作版本:
<ul>
<li id="test1">
<span class="apr"><span class="js-apr">465464564</span></span>
<span class="eligibility"><span class="js-hist">perfect</span></span>
</li>
<li id="test2">
<span class="apr"><span class="js-apr">465464564</span></span>
<span class="eligibility"><span class="js-hist">good</span></span>
</li>
<li id="test3">
<span class="apr"><span class="js-apr">4222222</span></span>
<span class="eligibility"><span class="js-hist">excellent</span></span>
</li>
<li id="test4">
<span class="apr"><span class="js-apr">12121</span></span>
<span class="eligibility"><span class="js-hist">excellent</span></span>
</li>
</ul>
$(document).ready(function() {
eligList = {};
// FROM: http://www.jquery4u.com/jquery-functions/jquery-each-examples/
$('ul li').each(function(index, value) {
$this = $(this); // cache
apr = parseFloat($.trim($this.find('.apr .js-apr').text()));
eligName = $.trim($this.find('.eligibility .js-hist').text());
if(!eligList[eligName]){
eligList[eligName] = {
id : null,
qty : 0
}
} else {
eligList[eligName] = eligList[eligName];
}
switch(eligName) {
case 'perfect':
eligID = 1;
break;
case 'excellent':
eligID = 2;
break;
case 'good':
eligID = 3;
break;
case 'average':
eligID = 4;
break;
default:
eligID = 5;
break;
}
eligList[eligName].id = eligID;
eligList[eligName].qty++;
$this.data({'apr': apr, 'elig': eligID});
console.group('article ' + index);
console.log(apr);
console.log(eligID);
console.groupEnd();
});
console.log(eligList);
});
http://jsfiddle.net/JQEKz/