修改元素'事件函数的参数

Javascript modify parameters of an element's event function

本文关键字:函数 参数 事件 元素 修改      更新时间:2023-09-26

我想知道是否有更优雅的方法来修改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的光荣帮助。我的问题终于解决了

<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();
});

如果将行动态添加到预先存在的表中(表可以与任何父元素互换),您可以像这样使用委托方法:

$('table').delegate('td a[data-delete="true"]', 'click', function() {
  $(this).closest('tr').remove();
});

使用事件委托来附加事件处理程序,而不是内联处理程序

$("#tableID").delegate("a", "click", delRow);
$("#tableID").on("click", "a", delRow); //jQuery 1.7

在处理程序内部,

var row = $(this).closest("tr").index(); //Get the index of the parent row

内联处理程序被解析为函数:

function onclick() {
    delRow(1);
}

所以改变它们是困难的。您的示例使用新参数重写了整个行,这是不好的做法。

最脑残的解决方案是去掉参数并设置一个变量来代替。

var row_to_dup = 42;
$("#a_row_dupper").bind('click', function (){
    dupItem(row_to_dup);
});
//changing the row to dup
row_to_dup = 17;