我有一张桌子,我想要一个“添加行”功能。我正在做的是当按下按钮时克隆行然后被添加,并且更改了id,表单元素的名称和onchange事件。所有这些都有效,除了onchange函数总是调用最新的id。所以有3行(id为1,2和3),我在第2行更改时触发,第3行传递给处理程序而不是2。
这是脚本:
function addRow(){
count = parseInt($("#hidden_count").val())
count++
$("#hidden_count").val(count)
var row = $("#add_box").prev().clone()
row.attr("id", "row_" + count)
row.children().each(function(index, elem){
if(elem.id.indexOf("delete_col_") != -1){
elem.id = "delete_col_" + count
$(elem).empty()
$(elem).append("<div class='table-row-delete' onclick='deleteRow("+count+")'></div>");
}else{
$(elem).children().each(function(index, elem){
if(typeof elem.name != 'undefined'){
if(elem.name.indexOf("exhaust_filter_num") != -1){
elem.name = "sheet[exhaust_filter_num_" + count + "]"
elem.value = parseInt(elem.value) + 1
}else if(elem.name.indexOf("exhaust_filter_size") != -1){
elem.name = "sheet[exhaust_filter_size_" + count + "]"
elem.id = "exhaust_filter_size_" + count
elem.onchange = function() { calculateRow(count) }
}else if(elem.name.indexOf("exhaust_velocity") != -1){
elem.name = "sheet[exhaust_velocity_" + count + "]"
elem.id = "exhaust_velocity_" + count
elem.value = 0
elem.onchange = function() { calculateRow(count) }
}else if(elem.name.indexOf("exhaust_cfm") != -1){
elem.name = "sheet[exhaust_cfm" + "_" + count + "]"
elem.id = "exhaust_cfm_" + count
elem.value = 0
}
}
})
}
})
row.insertBefore("#add_box")
}
function calculateRow(id){
var filter = $("#exhaust_filter_size_" + id).val()
console.log("Calc row: " + id + ", " + filter)
var velocity = parseInt($("#exhaust_velocity_" + id).val())
var cfmElem = $("#exhaust_cfm_" + id)
var cfm = velocity * filterData[filter].freeArea * filterData[filter].kFactor
cfmElem.val(cfm)
}
orignal html是这样排列的(它很长,所以这是一个剥离版本):
<table>
<tr id="row_1">
<td><input onchanged="calculateRow(1)" /></td>
...
</tr>
<tr id="add_box" align="center">
<td colspan="5"><input type="button" value="Add Row" onclick="addRow();"/></td>
<input type="hidden" id="hidden_count" value="1" />
</tr>
</table>
答案 0 :(得分:1)
您需要使用count
关键字var
作为var count = parseInt($("#hidden_count").val());
本地变量:
{{1}}