我有一组列表项,用于保存输入和选择框。我试图遍历列表项,抓取它们内部的值,然后根据这些数字运行一个函数,结果推入一个数组。我很遗憾地努力让我的点击功能正确。
计算功能
function calculateSum(power, amountItem, usage) {
var finalSum;
if (power && amountItem && usage != null) {
finalSum = (power * amountItem * usage)/1000;
} else {
console.log('Parameters not passed into calculateSum function');
}
return finalSum;
};
点击功能 - 我正在努力的部分。
calculationsArray = [];
$('#calculate-this').on('click', function(){
$('#calculation-options li').each( function() {
var power = $('.wattage select').val();
var amount = $('.quantity-output').val();
var usage = $('.usage select').val();
var calculationResult = calculateSum(power, amount,usage);
console.log(calculationResult);
calculationsArray.push(calculationResult);
});
});
示例HTML Li结构
<ul id="calculation-options">
<li id="item-1">
<div>
<img data-name="item-1" id="item-1" src="img/item1.png" alt="Begin Process"/>
</div>
<div class="controls-wrapper">
<div class="controls-wrapper-inner">
<input name="quantity" class="quantity-output quantity-value-1" value="5">
<div class="controls-wrapper-selector">
<a data-id="1" class="minus">-</a>
<a data-id="1" class="plus">+</a>
</div>
</div>
</div>
<div class="power">
<select>
<option selected="selected" value="POWER">Power</option>
<option value="70">70w</option>
<option value="100">100w</option>
</select>
</div>
<div class="Usage">
<select>
<option selected="selected" value="usage">Usage</option>
<option value="1">1 Hours</option>
<option value="2">2 Hours</option>
</select>
</div>
</li>
<li id="item-2">
<div>
<img data-name="item-2" id="item-2" src="img/item2.png" alt="Begin Process"/>
</div>
<div class="controls-wrapper">
<div class="controls-wrapper-inner">
<input name="quantity" class="quantity-output quantity-value-1" value="5">
<div class="controls-wrapper-selector">
<a data-id="1" class="minus">-</a>
<a data-id="1" class="plus">+</a>
</div>
</div>
</div>
<div class="power">
<select>
<option selected="selected" value="POWER">Power</option>
<option value="70">70w</option>
<option value="100">100w</option>
</select>
</div>
<div class="Usage">
<select>
<option selected="selected" value="usage">Usage</option>
<option value="1">1 Hours</option>
<option value="2">2 Hours</option>
</select>
</div>
</li>
</ul>
<a id="calculate-this">Calculate This!</a>
任何方向都会很棒!
d
答案 0 :(得分:1)
jQueryElement.each( ... )
采用带有2个参数的函数引用,第一个是索引,第二个是元素。使用该元素对你有利。
$('#calculation-options li').each( function( i, elem ) {
console.log( $(elem).find( 'option:selected' ) );
} );