首页 > 解决方案 > jQuery 事件范围不起作用

问题描述

我有一个包含表格的页面,但我想让用户选择使其中一个字段可编辑。

在我拥有的其中一个牢房中

<a class='noteedit'><i class='material-icons blue-text'>edit</i></a>

在我的 JS 我有

$(".noteedit").click(function(){
    obj = $(this).parent().parent(); // get entire row
    cell = $(obj).find("td:eq(1)"); // get current value of cell
    $(obj).find("td:eq(2)").remove(); // remove adjacent cell
    cell.replaceWith("<td><form><input name='noteedit' value='" + cell.text() +"'></td><td><a onclick=\"$(this).parent().parent().find('form').submit();\"  class='noteeditsubmit'><i class='material-icons green-text'>send</i></a><a  class='noteeditcancel'><i class='material-icons grey-text'>cancel</i></a></form></td>") // Change cell to become a form and change adjacent cell be the submit button.
    $(".noteeditcancel").click(function(){
        // Convert cell from <form> to just its original value
        // Change Submit/Cancel icon to original Edit button
    });
});

问题是一旦我将单元格值转换为原始编辑按钮,我就不能再单击该按钮,因为事件绑定不在范围内。

那么,我该如何解决这个问题并获得比我现在正在做的更好的解决方案。

我的目标是有一个编辑按钮,可以将单元格转换为可提交的表单,但也有一个取消按钮来恢复原始值

标签: javascriptjqueryforms

解决方案


您不应该在另一个事件处理程序中拥有一个事件处理程序。您可以使用类(甚至是动态创建的)$(document).on('click', '.noeeditcancel', function(){})来监听所有元素的点击事件。noeeditcancel您可以通过这种方式在文档中与您的查询匹配的所有元素上侦听事件。

$(".noteedit").click(function(){
    obj = $(this).parent().parent(); // get entire row
    cell = $(obj).find("td:eq(1)"); // get current value of cell
    $(obj).find("td:eq(2)").remove(); // remove adjacent cell
    cell.replaceWith("<td><form><input name='noteedit' value='" + cell.text() +"'></td><td><a onclick=\"$(this).parent().parent().find('form').submit();\"  class='noteeditsubmit'><i class='material-icons green-text'>send</i></a><a  class='noteeditcancel'><i class='material-icons grey-text'>cancel</i></a></form></td>") 
});
$(document).on('click', '.noteeditcancel', function(){

});

推荐阅读