簡體   English   中英

Javascript修改元素的事件函數的參數

[英]Javascript modify parameters of an element's event function

我想知道是否有更優雅的方法來修改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();
});

更新

如果將行動態添加到預先存在的表(表可以與任何父元素互換),則可以使用委托方法,如下所示:

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

所以改變它們很困難。 您的示例使用新參數重寫了整個行,​​這是一種不好的做法。

最死腦筋的解決方案是擺脫參數並設置變量istead。

var row_to_dup = 42;

$("#a_row_dupper").bind('click', function (){
    dupItem(row_to_dup);
});

//changing the row to dup
row_to_dup = 17;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM