如果用户按下回车键或在外部单击,则保留元素的新html值

Keep new html val of an element if the user presses enter or clicks outside

本文关键字:保留 元素 html 单击 外部 用户 回车 如果      更新时间:2023-09-26

我正试图用下面的代码段找到一种方法,当用户单击<input>之外的其他位置时,将.text(newContent)值放入编辑过的单元格中。

目前,它只在用户按下键盘上的Enter键时工作。我尝试过在keypress函数中添加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>

原来有一些问题(嵌套处理程序从来都不是一个好主意,因为会发生多个事件)。我使用委托的处理人员在下面为您做了一次完整的重写。

JSFiddle:http://jsfiddle.net/TrueBlueAussie/ckk4ab3x/

这使用委托的事件处理程序来允许动态创建控件。它还针对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();
    });
});