javascript 使用 Jquery 获取并遍历表中的所有选择框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5110244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get and loop through all Select Boxes in a Table with Jquery
提问by toddm
i am new with jQuery.. i have a table with a number of boxes in it. I want to grab all the select boxes in the table and loop through them..
我是 jQuery 的新手。我有一张桌子,里面有很多盒子。我想抓取表格中的所有选择框并循环遍历它们..
I am trying to create a function that does this and it looks like this:
我正在尝试创建一个执行此操作的函数,它看起来像这样:
function calculatePercentageTotal(tableName) {
var total = 0;
for (i = 0; i <= $("#" + tableName + ' select').length; i++) {
total += parseInt($("#" + tableName + ' select')[i].val());
}
return total;
}
It's not working though.. any ideas? thanks!
虽然它不起作用..有什么想法吗?谢谢!
回答by Kae Verens
this should do it:
这应该这样做:
function calculatePercentageTotal(tableName) {
var total=0;
$('#'+tableName+' select').each(function(){
total+= +($(this).val());
});
return total;
}
回答by DidierDotNet
Just use a selector to get the elements. I'm not sure which elements you are looking for. If what you are trying to do is to sum the values of the selected items in all the selects(dropdowns) then you can use this:
只需使用选择器来获取元素。我不确定您要寻找哪些元素。如果您想要做的是对所有选择(下拉列表)中所选项目的值求和,那么您可以使用:
var mysum = 0;
$("#" + tableName.id + ' select').each(function(){
mysum += $(this).val() * 1;
});
alert("mysum = " + mysum.toString);
// Why **"$(this).val() * 1"** - .val() will return a string with the value selected
// * 1 will make it numeric.
回答by indra
$(document).ready(function(){
var total =0;
$("#calculatebtn").click( function(e){
$("select").each(function(){
total += parseInt($(this).val());
});
alert("total=" + total);
});
});
You need a button with id='calculatebtn'
你需要一个带有 id='calculatebtn' 的按钮

