在“输入”上,使输入元素在单元格中消失,但保留文本内容

On "enter" make input element dissapear in the cell, but leave the text content

本文关键字:输入 保留 文本 消失 元素 单元格      更新时间:2023-09-26

我想用javascript更改单元格内容。当我单击一个单元格时,会出现一个input元素,该元素获取单元格文本的值。当我单击输入时编辑输入元素中的文本后,我希望单元格再次正常(没有输入元素)。

下表如下:

<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>

这是Javascript:

$("td").click(function(){
  if($(this).find("input").length==0){
    var cellContent = $(this).html();
    $(this).empty();
    $(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
    $(this).find("input").focus();
}});// this part creates input element in a cell 
现在,当

新内容应保留在单元格中但没有输入元素时,按回车键后出现问题。

$("td").click(function(){
  var newCellContent = $("input",this).val();
  console.log(newCellContent);
  $("input").keyup(function(event){
    if(event.which == 13){
      $(this).empty();
      $(this).html(newCellContent);
    }
    newCellContent = $("input",this).val();
  });
});

我个人建议使用 CSS 来显示/隐藏<input>元素,并使用 JavaScript 仅处理值的传输和按 Enter<input>的模糊,如下所示:

// finding the <table> element containing the <input> elements,
// and adding an event-listener:
document.querySelector('table').addEventListener('keyup', function(e) {
  // 'e' is the event itself.
  // caching the element that triggered the keyup event:
  var current = e.target,
    // caching its tagName, in lower-case:
    tag = current.tagName.toLowerCase(),
      // we're using this check twice, so caching the result,
      // checking that the tag is equal to 'input', and that
      // the element has a 'type' property, and that the
      // current type is equal to 'text':
      isRelevantInput = tag === 'input' && current.type && current.type === 'text';
  // if the check returns true, and the key pressed (e.which) is
  // equal to 13 (the enter key):
  if (isRelevantInput && e.which === 13) {
    // we blur the element (allowing the CSS
    // to show the <label> text again, and hide
    // the <input>:
    current.blur();
  }
  // otherwise, if only the check itself is true
  // (note that the most difficult-to-satisfy condition
  // goes first):
  else if (isRelevantInput) {
    // we update the textContent of the <input> element's
    // next element-sibling (the <span> in this example)
    // to the current value of the <input> element:
    current.nextElementSibling.textContent = current.value;
  }
});
// Using Function.prototype.call() to use Array.prototype.forEach()
// to iterate over the NodeList returned from
// document.querySelectorAll():
Array.prototype.forEach.call(document.querySelectorAll('table label > input'), function (input) {
  // the first argument of the anonymous function (here: 'input')
  // is the array-element of the array over which we're iterating.
  // setting the value of the <input> to the textContent of
  // of its next element-sibling (the <span> containing the
  // text of the parent <label> associated with the <input>:
  input.value = input.nextElementSibling.textContent;
});

上面的 JavaScript 与这个 CSS 相结合:

td {
  height: 2em;
}
label > input {
  /* we're not using 'display: none' in
     order that the <input> elements can
     receive focus: */
  opacity: 0;
  height: 0;
}
/* once focused the <input>
   has a defined height and
   a visible opacity: */
label > input:focus {
  opacity: 1;
  height: 1.5em;
}
/* forcing the <span> to the
   next line of the <td>: */
label > input + span {
  display: block;
  height: 1.5em;
}
/* hiding the <span> when the
   <input> has focus: */
label > input:focus + span {
  display: none;
}

对于 HTML:

<table>
  <tr>
    <td>
      <!-- wrapping the <input> in a <label> element
           means that clicking the <label> text will
           focus the <input>, using CSS to show the
           <input> and hide the <span>: -->
      <label>
        <input type="text" /><span>Content 1</span>
      </label>
    </td>
    <!-- repeated content removed for brevity -->
  </tr>
</table>

document.querySelector('table').addEventListener('keyup', function(e) {
  var current = e.target,
    tag = current.tagName.toLowerCase(),
      isRelevantInput = tag === 'input' && current.type && current.type === 'text';
  if (isRelevantInput && e.which === 13) {
    current.blur();
  }
  else if (isRelevantInput) {
    current.nextElementSibling.textContent = current.value;
  }
});
Array.prototype.forEach.call(document.querySelectorAll('table label > input'), function (input) {
  input.value = input.nextElementSibling.textContent;
});
td {
  height: 2em;
}
label > input {
  opacity: 0;
  height: 0;
}
label > input:focus {
  opacity: 1;
  height: 1.5em;
}
label > input + span {
  display: block;
  height: 1.5em;
}
label > input:focus + span {
  display: none;
}
<table>
  <tr>
    <td>
      <label>
        <input type="text" /><span>Content 1</span>
      </label>
    </td>
    <td>
      <label>
        <input type="text" /><span>Content 2</span>
      </label>
    </td>
    <td>
      <label>
        <input type="text" /><span>Content 3</span>
      </label>
    </td>
  </tr>
  <tr>
    <td>
      <label>
        <input type="text" /><span>Content 4</span>
      </label>
    </td>
    <td>
      <label>
        <input type="text" /><span>Content 5</span>
      </label>
    </td>
    <td>
      <label>
        <input type="text" /><span>Content 6</span>
      </label>
    </td>
  </tr>
</table>

但是,使用您当前的 HTML 并使用 jQuery,我建议:

// finding the relevant <td> elements,
// using on() to attach an anonymous
// click event-handler:
$('table td').on('click', function() {
  // creating an <input> element,
  // setting its 'type' and 'value'
  // properties:
  var input = $('<input />', {
    'type': 'text',
    'value': this.textContent
  // appending the created <input> to the <td> (this/$(this))
  // after emptying the <td> using empty(), and focusing the
  // created <input>:
  }).appendTo($(this).empty()).focus();
// binding an keyup event-handler using on(),
// passing the event ('e') to the function:
}).on('keyup', function(e) {
  // if it was the enter key that was pressed:
  if (e.which === 13) {
    // finding the <input> element with find(),
    // and caching the result:
    var input = $(this).find('input');
    // inserting the text string of the current
    // value of the <input> before the <input>,
    // and then removing the <input>:
    input.before(input.val()).remove();
  }
});

$('table td').on('click', function() {
  var input = $('<input />', {
    'type': 'text',
    'value': this.textContent
  }).appendTo($(this).empty()).focus();
}).on('keyup', function(e) {
  if (e.which === 13) {
    var input = $(this).find('input');
    input.before(input.val()).remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Content 1</td>
    <td>Content 2</td>
    <td>Content 3</td>
  </tr>
  <tr>
    <td>Content 4</td>
    <td>Content 5</td>
    <td>Content 6</td>
  </tr>
</table>

引用:

  • .CSS:
    • 相邻同级(+)组合子。
    • 子(>)组合器。
    • :focus伪类。
  • .HTML:
    • <input> .
    • <label> .
    • <span> .
  • JavaScript:
    • Array.prototype.forEach() .
    • document.querySelector() .
    • document.querySelectorAll() .
    • eventTarget.addEventListener() .
    • Function.prototype.call() .
    • KeyboardEvent.key .
  • j查询:
    • appendTo() .
    • before() .
    • empty() .
    • find() .
    • remove() .
    • val() .

这是你必须做的

$(function(){
$("table td").on('click',function(){
    if($(this).find("input").length==0){
    var cellContent = $(this).html();
    $(this).empty();
    $(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
    $(this).find("input").focus();
}
});

注意:keyup函数中使用td Object之前,我如何先将存储在变量中。此外,您还需要使用remove()函数来删除元素。

 var newCellContent = $("input",this).val();
        var tdObject = $(this);

====

======================================================================
    $('table td').on('keyup',function(){
  var newCellContent = $("input",this).val();
        var tdObject = $(this); //Storing the td object in a variable
  $("table td input").keyup(function(event){
    if (event.keyCode == 13) {
        console.log($(this).val());
      $(this).remove(); // remove() removes an html element in this case input elem
      tdObject.html(newCellContent);
    }
    newCellContent = $("input",this).val();
  });
    });
});

查看小提琴链接

您的参考资料:

jQuery DOCS remove()

我会尝试识别不同的任务并为其分配功能(addInput()添加一个输入,removeInputs()删除任何以前打开的输入)。试试吧:

var shownInputs = [];
$("td").click(function () {
    if (!$(this).find("input").length) {
        removeInputs();
        addInput($(this));
    }
});
function addInput(el) {
    var cellContent = el.html();
    el.html("<input type='text' size='" + cellContent.length + "' value='" + cellContent + "'>");
    el.find("input").focus().keyup(function (e) {
        var keycode = e.keyCode ? e.keyCode : e.which;
        if (keycode == 13) {
            removeInputs();
        }
    });
    shownInputs.push(el);
}
function removeInputs() {
    $.each(shownInputs, function (i, el) {
        el.html(el.find("input").val());
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Content 1</td>
        <td>Content 2</td>
        <td>Content 3</td>
    </tr>
    <tr>
        <td>Content 4</td>
        <td>Content 5</td>
        <td>Content 6</td>
    </tr>
</table>

您可以在

创建input后立即在第一个单元格click处理程序中注册keyup处理程序:

$("td").click(function(){
  if($(this).find("input").length==0){
    var cellContent = $(this).html();
    $(this).empty();
    $(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
    $(this).find("input").focus();
    // > Added
    $(this).find("input").keyup(function(event){
        if(event.which == 13){
            var newCellContent = $(this).val();
            $(this).parent().html(newCellContent);
            $(this).remove();         
        }
    }).focus();
    //
}});// this part creates input element in a cell

查看演示

小提琴链接 - 试试吧。下面的代码

您不需要多次单击绑定

$("td").click(function () {
    if ($(this).find("input").length === 0) {
        var cellContent = $(this).html();
        $(this).empty();
        $(this).append("<input type='text' size='" + cellContent.length + "'     value='" + cellContent + "'>");
        $(this).find("input").focus();
    }
    currentTd = $(this);
    $("input").keydown(function (event) {
        if (event.which == 13) {
            $(this).remove();
            $(currentTd).html($(this).val());
        }
    });
});

$("input").keyup(function(event){}中使用$(this)会将函数(如.empty())应用于输入。

您可以通过多种方式解决此问题:

  • 请改用$(this).closest('td').empty():这将查找要应用函数的父"td"。
  • 创建一个包含 td 元素的变量,并使用它来应用于函数。

另外:使用 .html() 设置 html 将覆盖当前内容,因此无需执行.empty()

示例代码(也清理了一点):

jQuery().ready(function(){
  $("td").click(function(){
    if($(this).find("input").length==0){
      var cellContent = $(this).html();
      $(this).empty();
      $(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
      $(this).find("input").focus().keyup(function(event){
        if(event.which == 13){
          $(this).closest("td").html($(this).val());
        }
      });
  }});// this part creates input element in a cell
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>

你在错误的范围内做你的逻辑,本质上是针对输入。以下内容现在应该可以工作了。

$("td").click(function(){
  var newCellContent = $("input",this).val();
  console.log(newCellContent);    $("input").keyup(function(event){
    if(event.which == 13){
      $(this).parent().empty();
      $(this).parent().html(newCellContent);
    }
    newCellContent = $("input",this).val();
  });
});

因为你keyup事件绑定到动态创建的元素(inputs),所以你必须在body上使用on函数

$("td").click(function(){
  if($(this).find("input").length==0){
    var cellContent = $(this).html();
    $(this).empty();
    $(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
    $(this).find("input").focus();
}});// this part creates input element in a cell 
$('body').on('keyup', 'input', function(event) { // code
    if(event.keyCode == 13){
      $(this).parent( "td" ).html($(this).val());
    }    
});

这是适合您的
工作演示https://jsfiddle.net/o2ka4qnb/