使用JQuery创建按钮并单击处理程序

时间:2015-09-29 22:38:55

标签: javascript jquery html onclick event-handling

目前我正在显示一个值表,其中最后一列提供了一个"编辑"和"删除"选项。为简单起见,当他们编辑一行时,我只是清除每列的innerHTML并将输入字段放在那里。我还需要使用Save / Cancel替换Edit / Delete链接,但是我需要使用JS / JQuery创建这些按钮,附加点击处理程序将它们附加到innerHTML。

虽然我找到了类似的例子,但我不清楚如何做到这一点,并希望得到任何帮助。

function editRecord(line)
{
    var zone = "<?= $data['zone']; ?>";

    // Store the original field values
    var valueName = document.getElementById("entryName" + line).innerHTML;
    var valueTTL = document.getElementById("entryTTL" + line).innerHTML;
    var valueAddress = document.getElementById("entryAddress" + line).innerHTML;

    // Replace existing row value with input fields to make edits
    document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + valueName + "'>";
    document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + valueTTL + "'>";
    document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + valueAddress + "'>";

    // Create Save button with click handler
    // Create Cancel button with click handler
    // Append these to the element below (replacing the Edit/Delete)

    document.getElementById("entryOptions" + line).innerHTML = "<input type='button' value='Save'> <input type='button' value='Cancel'>";
}

1 个答案:

答案 0 :(得分:0)

经过进一步的修补,我设法弄明白了。如果最终帮助其他人,那么这是工作代码。

function editRecord(line)
{
    var zone = "<?= $data['zone']; ?>";

    // Store the original field values
    var originalName = document.getElementById("entryName" + line).innerHTML;
    var originalTTL = document.getElementById("entryTTL" + line).innerHTML;
    var originalAddress = document.getElementById("entryAddress" + line).innerHTML;

    // Replace existing row value with input fields to make edits
    document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + originalName + "'>";
    document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + originalTTL + "'>";
    document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + originalAddress + "'>";

    document.getElementById("entryOptions" + line).innerHTML = "";

    var saveButton = $('<button/>', {
        text: "Save",
        id: 'btn_Save' + line,
        click: function ()
        {
            // Save the changes
        }
    });

    var cancelButton = $('<button/>', {
        text: "Cancel",
        id: 'btn_Cancel' + line,
        click: function ()
        {
            document.getElementById("entryName" + line).innerHTML = originalName;
            document.getElementById("entryTTL" + line).innerHTML = originalTTL;
            document.getElementById("entryAddress" + line).innerHTML = originalAddress;
        }
    });

    $("#entryOptions" + line).append(saveButton);
    $("#entryOptions" + line).append(cancelButton);
}