我有一张桌子,我想要一个“添加行”功能。我正在做的是当按下按钮时,该行被克隆然后附加,并且表单元素的 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)
}
原始 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>