javascript - 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
});
});
问题是一旦我将单元格值转换为原始编辑按钮,我就不能再单击该按钮,因为事件绑定不在范围内。
那么,我该如何解决这个问题并获得比我现在正在做的更好的解决方案。
我的目标是有一个编辑按钮,可以将单元格转换为可提交的表单,但也有一个取消按钮来恢复原始值
解决方案
您不应该在另一个事件处理程序中拥有一个事件处理程序。您可以使用类(甚至是动态创建的)$(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(){
});
推荐阅读
- python - 子采样数据,使得从包含 N 个类的巨大数据集中选择至少 K 个类
- xaml - 图像不会在 Xamarin Forms 中显示
- stripe-payments - 如果我只想在购买时保存用户的信用卡,则有关 `setup_future_usage: "off_session"` 和 `confirmCardSetup` 的条纹差异
- linux - 按特定顺序多线程处理文件的算法
- python-3.x - 为什么我的函数返回 None 而不是数字?
- javascript - 按字母顺序排列对象数组中的对象数组
- php - 如何从 foreach 循环中获取变量?
- javascript - 尝试使用默认配置和运行时未找到预设的 vue-test-utils-getting-started
- c++ - MFC 中的窗口消息管理:是否必须添加基类调用?
- kotlin - 黄瓜 + JUnit5 + gradle + kotlin