在动态创建元素时不使用(选择器)
问题描述:
代码基本上编辑表格单元格。 我想使用not()方法,以便每次在创建的临时输入之外单击时,都将其替换为表格单元格。我猜代码运行在一个块中,并没有检测到任何输入的ID为“替换”,所以我该如何解决这个问题? 另外我想存储引发第一个事件(dblclick)的元素(th或td),以便我可以用它来替换具有正确类型单元格的输入,但它似乎只存储首先触发事件的元素我不明白为什么。在动态创建元素时不使用(选择器)
的完整代码here
$(function() {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function() { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
答
我已经修改HTML和JavaScript,以避免任何可能的错误。正确的做法是将所有th
的thead
和所有td
的。
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>
要绑定一个新的,额外的'click'你打开一个文本框,每一次处理程序。这将迅速失控。无论如何,因为只有一个'body',并且它没有ID'#replace',你的'.not()'是没用的。相反,一次绑定到'body' *,检查是否存在'#replace'但不是事件的目标,然后继续。 –