将文本元素在单击时转换为输入字段类型文本,并在单击离开时更改回文本

Turn text element into input field type text when clicked and change back to text when clicked away

本文关键字:文本 单击 离开 回文 输入 转换 元素 字段 类型      更新时间:2023-09-26

我正在尝试创建一个表单,字段在飞行中变化。

从简单的文本开始,当有人点击这个文本时,它会转移到可编辑的文本输入字段。当有人点击离开时,它会变成不可编辑的文本。

我试了一下,但它似乎不能正常工作。在前几次点击上工作得很好,但随后它丢失了inputId并混合了按钮。

这里是html

<p id="firstElement" onclick="turnTextIntoInputField('firstElement');">First Element</p>
<p id="secondElement" onclick="turnTextIntoInputField('secondElement');">Second Element</p>

这里是JavaScript(使用jQuery)。

我对JavaScript很陌生,所以它可能不是最好的质量代码…

function turnTextIntoInputField(inputId) 
{  
    console.log(inputId);
    inputIdWithHash = "#"+inputId;
    elementValue = $(inputIdWithHash).text();
    $(inputIdWithHash).replaceWith('<input name="test" id="'+inputId+'" type="text" value="'+elementValue+'">');
    $(document).click(function(event) { 
        if(!$(event.target).closest(inputIdWithHash).length) {
            $(inputIdWithHash).replaceWith('<p id="'+inputId+'" onclick="turnTextIntoInputField('''+inputId+''')">'+elementValue+'</p>');
        }      
    });
}

下面是关于小提琴的实例https://jsfiddle.net/7jz510hg/

我将感谢任何帮助,因为它让我头疼…

首先,你不需要在html本身中使用onclick

还有另一种方法:

/**
  We're defining the event on the `body` element, 
  because we know the `body` is not going away.
  Second argument makes sure the callback only fires when 
  the `click` event happens only on elements marked as `data-editable`
*/
$('body').on('click', '[data-editable]', function(){
  
  var $el = $(this);
  var $input = $('<input/>').val( $el.text() );
  $el.replaceWith( $input );
  
  var save = function(){
    var $p = $('<p data-editable />').text( $input.val() );
    $input.replaceWith( $p );
  };
  
  /**
    We're defining the callback with `one`, because we know that
    the element will be gone just after that, and we don't want 
    any callbacks leftovers take memory. 
    Next time `p` turns into `input` this single callback 
    will be applied again.
  */
  $input.one('blur', save).focus();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-editable>First Element</p>
  
<p data-editable>Second Element</p>
  
<p>Not editable</p>

小提琴:https://jsfiddle.net/7jz510hg/1/

问题是没有用var定义inputIdWithHash和elementValue变量,它们成为全局变量。

var inputIdWithHash
var elementValue

然后,由于它们具有全局作用域,因此它们的旧值可用于文档单击处理程序。你希望它们在turnTextIntoInputField函数的局部范围内。

和更新维护值:https://jsfiddle.net/7jz510hg/2/

边注,你使用的是jQuery 1.6,所以我不得不使用unbind函数而不是off。

更新小提琴:https://jsfiddle.net/7jz510hg/3/

这使用了最新的jquery,事件命名空间,所以我们可以附加多个点击事件到文档,因此允许我们在字段之间点击,而不会丢失任何东西。如果你直接点击字段,而不是点击字段,点击文档,点击字段,前一个小提琴会搞砸。

如果有人需要的话,我将Yura的答案从JQuery移植到Vanilla JavaScript。这个也适用于p, h1, h2, span,等等

function editData(e) {
  const el = e.target;
  const input = document.createElement("input");
  input.setAttribute("value", el.textContent);
  el.replaceWith(input);
  const save = function() {
    const previous = document.createElement(el.tagName.toLowerCase());
    previous.onclick = editData;
    previous.textContent = input.value;
    input.replaceWith(previous);
  };
  /**
    We're defining the callback with `once`, because we know that
    the element will be gone just after that, and we don't want 
    any callbacks leftovers take memory. 
    Next time `p` turns into `input` this single callback 
    will be applied again.
  */
  input.addEventListener('blur', save, {
    once: true,
  });
  input.focus();
}
for (const child of document.querySelectorAll('[data-editable]')) {
  child.onclick = editData;
}
<h1 data-editable>First h1</h1>
<p data-editable>First Element</p>
  
<p data-editable>Second Element</p>
  
<p>Not editable</p>

相关:

  • JS等价于jQuery one()

我建议,不要把事情弄复杂。我使用一个简单的隐藏和显示方法将文本更改为输入字段。这是非常容易实现和理解的。

 $('#editable').on('click',function(){
     var groupname = $("#editable").html();
     $("#editable").css({'display':"none"});
     $("#inputgroupname").css({'display':'block'});
     $("#inputgroupname").focus();
      $("#inputgroupname").val(groupname);
});
$("#inputgroupname").focusout(function(){
   $('#editable').html($("#inputgroupname").val());
  $("#inputgroupname").css({'display':'none'});
  $("#editable").css({'display':"block","margin-top":"2px"});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="box-title" style="margin-top:2px; margin-left:5px;" id="editable">Hello</h3>
 <input type="text"  id="inputgroupname" style="display:none;">

试试这个

$('#tbl').on('click','.editable',function() {
  var t = $(this);          
  var input = $('<input>').attr('class', 'savable').val( t.text() );
  t.replaceWith( input ); 
  input.focus();
});
$('#tbl').on('blur','.savable',function() {
  var input = $(this);      
  var t = $('<span>').attr('class', 'editable').text( input.val() );
  input.replaceWith( t ); 
});
http://jsfiddle.net/yp8bt6s0/