我正在尝试使用以下代码片段找到一种方法来放置 .text(newContent)
当用户单击 <input>
中的其他位置时,将值写入编辑的单元格中.
目前,它仅在用户按键盘上的 Enter 时才起作用。我尝试添加 e.type == "click"
或e.which == 1
进入按键功能,但它无法工作,因为它是 <td>
上的事件细胞。
有没有办法删除 <input>
标记并在用户点击 td 外部时保留用户的值?
$(function () {
$(".td").click(function () {
var content = $(this).text();
if ( $(this).text() == '...' ) {
$(this).html('<input type="text" value="" size="8" />');
} else {
$(this).html('<input type="text" value="' + content + '" size="8" />');
}
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if ( e.which == 13 ) {
if ( $(this).val() == '' ) {
var newContent = '...'
$(this).parent().text(newContent);
} else {
var newContent = $(this).val();
$(this).parent().text(newContent);
}
}
});
});
});
#table td {
width: 50px;
border:1px solid #c0c0c0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table">
<tr>
<td class="td" data-res="1">...</td>
<td class="td" data-res="2">...</td>
<td class="td" data-res="3">...</td>
<td class="td" data-res="4">...</td>
<td class="td" data-res="5">...</td>
<td class="td" data-res="6">...</td>
<td class="td" data-res="7">...</td>
</tr>
</table>
最佳答案
原始版本有一些问题(嵌套处理程序从来都不是一个好主意,因为您会发生多个事件)。我在下面使用委托(delegate)处理程序为您进行了完整的重写。
JSFiddle:http://jsfiddle.net/TrueBlueAussie/ckk4ab3x/
这使用委托(delegate)事件处理程序来允许动态创建控件。它还针对 focusout
事件,这是您离开输入时得到的事件。
$(function () {
// Use a delegated event handler as the inputs are dynamic
$('#table').on('focusout', 'td input', function () {
var $input = $(this);
var $td = $input.closest('td');
var content = $input.val();
$td.html(content == "" ? "..." : content);
}).on('click', 'td', function () {
var $td = $(this)
var content = $td.text();
if (content == '...') {
content = "";
}
$td.html('<input type="text" value="' + content + '" size="8" />');
// Focus on the new input
$('input:first', $td).focus();
});
});
关于javascript - 如果用户按 Enter 或单击外部,则保留元素的新 html 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26138490/