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

时间:2015-06-13 12:13:28

标签: javascript jquery

我想用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 

现在问题出现在新的内容应该留在单元格但没有输入元素时按Enter键。

$("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();
  });
});

8 个答案:

答案 0 :(得分:2)

我个人建议使用CSS来显示/隐藏<input>元素,并使用JavaScript仅处理值的传输以及按<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>

参考文献:

答案 1 :(得分:1)

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

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

  • 请改为使用$(this).closest('td').empty():这会查找父母&#39; td&#39;将功能应用于。
  • 创建一个包含td元素的变量,并使用它来应用函数。

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

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

&#13;
&#13;
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
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你在错误的范围内做你的逻辑,这实际上是针对输入。以下应该现在可以使用。

$("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();
  });
});

答案 3 :(得分:1)

我会尝试识别不同的任务并为其分配功能(SELECT t1_1.name|| ' vs ' || t1_2.name FROM table_2 t2 JOIN table_1 t1_1 ON t2.user1_id = t1.user_id JOIN table_1 t1_2 ON t2.user2_id = t2.user_id where t2.match_id = 1; 添加输入,addInput()删除以前打开的任何输入)。试试吧:

&#13;
&#13;
removeInputs()
&#13;
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());
    });
}
&#13;
&#13;
&#13;

答案 4 :(得分:1)

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

$("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

请参阅demo

答案 5 :(得分:1)

这是你必须要做的事情

$(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();
}

});

注意:我如何在td Object函数中使用keyup之前先将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();
  });

    });

});

=============================================== =====================

<a href="#" class="btn cta map-trigger" data-lat="41.8911684" data-lng="12.507724100000019"> Show Map </a>

查看 FIDDLE LINK

您的参考文献:

jQuery DOCS remove()

答案 6 :(得分:1)

Fiddle link - 尝试一下。代码

您不需要多次点击绑定

$("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());
        }
    });

});

答案 7 :(得分:0)

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

$("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/