我建议,为了处理求和,将 jQuery 更改为:
$('#butt').click(function () {
/* this gets an array of the numbers contained within visible
input elements */
var nums = $('.list input:visible').map(function () {
return parseInt(this.value, 10);
}),
// initialises the total variable:
total = 0;
/* iterates over the numbers contained within the array,
adding them to the 'total' */
for (var i = 0, len = nums.length; i < len; i++) {
total += nums[i];
}
var msg = '';
if (isNaN(total)) {
msg = 'Input three numbers, please...';
} else if (total < 30) {
msg = "That's bad, should be higher...";
} else if (total > 40) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
$('#output').text(msg);
});
而且也不使用id
属性来选择要求和的元素,而是使用class
-names:
<div class="list owner">
<p>a</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>b</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>c</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for owners -->
</div>
<div class="list not-owner">
<p>x</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>y</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>z</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for non-owners -->
</div>
JS 小提琴演示。
测试某人是否是或说他们是所有者:
var total = 0,
isOwner = $.trim($('.myOptions option:selected').val()) === 'owner';
if (isOwner) {
console.log("It's the owner");
}
上面的 jQuery 耦合到一个select
元素,其中option
元素具有值:
<select class="myOptions">
<option value="-1" data-val="" selected>Pick an option</option>
<option value="owner" data-val="owner">Owner</option>
<option value="not-owner" data-val="not-owner">Not Owner</option>
</select>
JS 小提琴演示。
参考: