jQuery到Javascript的转换

时间:2013-12-03 03:23:26

标签: javascript jquery

更新

我在按钮中插入了JavaScript函数。只是想将一些jQuery代码转换为纯js因为我无法使用 $(this)访问代码。

我的代码:

function editcheck(el) {
    $(el).parent().parent().remove();
    var tableData = $(el).closest('#paytable tr').children("td").map(function () {
    return $(el).text();
}).get();

$('#checkamount').val($.trim(tableData[1]));
}
在调用 editcheck 之前

代码/函数:

var table = document.getElementById('paytable');
table.innerHTML += '<tr id="checktitle" style="border: none;"><td width="137px"><label>CHECK</label></td>' +
                    '<td class="rowAdd" width="125px">' + checkamounts.join("") + '</td>' +
                    '<td width="127px">' + checknos.join("") + '</td>' +
                    '<td style="display: none">' + dbank.join("") + '</td>' +
                    '<td style="display: none">' + draweedesc.join("") + '</td>' +
                    '<td style="display: none">' + pickercheck.join("") + '</td>' +
                    '<td><button title="Edit" onclick="editcheck(this)" type="button" style="width: 30px; height: 18px"><img src="images/editimg.png" width="13" height="13"></button></td>';

P.S 我不能使用 $(“#elementid”)。点击(function(),因为该行在追加后会存在。

1 个答案:

答案 0 :(得分:1)

当您在内联处理程序editcheck中调用this时,它会引用窗口对象

您可以使用editcheck.call(this)

.call()传递自定义执行上下文
<button title="Edit" onclick="editcheck.call(this)" style="width: 30px; height: 18px">

或将点击的元素引用作为参数传递,如

<button title="Edit" onclick="editcheck(this)" style="width: 30px; height: 18px">

然后

function editcheck(el) {
    var $tr = $(el).closest('tr');
    var tableData = $tr.children("td").map(function () {
        return $(this).text();
    }).get();
    $tr.remove();
    $('#checkamount').val($.trim(tableData[1]));
}

解决方案使用事件委派

<button title="Edit" class="edit" type="button" style="width: 30px; height: 18px"><img src="images/editimg.png" width="13" height="13"></button>

然后

jQuery(function () {
    $('#Paytable').on('click', '.edit', function () {
        var $tr = $(this).closest('tr').remove();
        $('#checkamount').val($.trim($tr.find('td:first').text());
    });
})