我想知道是否有更优雅的方法来修改 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()
函数,因为它已被弃用。解决方案效果很好 - 希望它能帮助别人 :)
最佳答案
如果您将 html 更改为类似于以下内容:
<tr>
<td>
<a href="#" data-delete="true">delete</a>
</td>
</tr>
那么你的 javascript 可以是这样的:
$('td a[data-delete="true"]').on('click', function() {
$(this).closest('tr').remove();
});
更新
如果行被动态添加到预先存在的表中(表对于任何父元素都是可互换的),您可以像这样使用委托(delegate)方法:
$('table').delegate('td a[data-delete="true"]', 'click', function() {
$(this).closest('tr').remove();
});
关于Javascript修改元素事件函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8578969/