我想知道是否有一种更优雅的方法来修改onclick
事件的参数。我有一个表,我动态地添加/删除其中的元素,并重新索引行。每一行都有一个delete
链接,其中包含行的索引(和一个duplicate
链接),需要更新其参数以匹配修改后的行id。
目前我的程式码看起来像(简化)
<a onclick="delRow(1)">delete</a>
和JavaScript:...
html = element.innerHTML;
html = html.replace(/dupRow(\\d+)/g, "dupRow(" + newIndex + ")");
html = html.replace(/delRow(\\d+)/g, "delRow(" + newIndex + ")");
element.innerHTML = html
我希望它能成为
if (element.onclick != null) {
element.onclick.params[0] = newIndex;
}
有这样的方法吗?如果有帮助的话,我也有jQuery。
更新:
所以感谢@rich.okelly的光荣帮助我解决了我的问题
<script>
...
var newRow = '\
<tr>\
<td class="index" col="0">0</td>\
<td>this is content...</td>\
<td><a href="#" row-delete="true">Del</a></td>\
</tr>';
// re-index table indices in a non-efficient manner
function reIndexTable() {
$("#rpc-builder-table").find('.index').each(function (i) {
$(this).html(i)
})
}
// add row
function addRow() {
for (i = 0; i < $('#addRowCount').attr("value"); i++) {
$("#rpc-builder-table").append(newRow);
}
reIndexTable();
}
$(document).ready(function () {
// add row button
$('#addRowsButton').on('click', function () {
addRow();
});
// delete row
$('#rpc-builder-table').on('click', 'td a[row-delete="true"]', function () {
$(this).closest('tr').remove();
reIndexTable();
});
...
}
</script>
...
<div>
<label>Rows to add: </label>
<input id="addRowCount" value="1" size="2" />
<button id="addRowsButton">Add Row(s)</button>
</div>
<div><table id="rpc-builder-table"><tbody>
<tr>
<th>Idx </th>
<th>Some content (1)</td>
</tr>
</tbody></table></div>
...
我使用了.on()
函数而不是建议的.delegate()
函数,因为它已经被弃用了。解决方案运行良好-希望它能对某人有所帮助:)
3条答案
按热度按时间qv7cva1a1#
如果将html更改为类似以下内容的内容:
那么你的javascript可以是这样的:
更新
如果数据列是动态加入至预先存在的数据表(数据表可与任何父项目互换),您可以使用委派方法,如下所示:
ncgqoxb02#
使用事件委托附加事件处理程序,而不是内联处理程序
在处理程序内部,
内联处理程序被解析为函数:
因此很难更改它们。您的示例使用新参数重写了整行,这是一种不好的做法。
w46czmvw3#
最脑残的解决方案是去掉参数,设置一个变量。