我想知道是否有更优雅的方法来修改onclick事件的参数。我有一个表,我动态地添加/删除元素,我重新索引行。每行都有一个delete
链接,该链接具有需要更新参数以匹配修改的行ID的行索引(和duplicate
链接)。Javascript修改元素的事件函数的参数
目前我的代码看起来像(简体)
<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()
功能,因为它已被弃用。解决方法效果很好 - 希望它可以帮助别人:)
你以错误的方式去做这件事。考虑在你的函数中使用对象点击'this'的引用。最后,对删除链接的引用应该允许您查找需要删除的行。现在你不需要参数。 – 2011-12-20 16:56:48