javascript 单击时将文本元素转换为输入字段类型文本,并在单击时变回文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33267797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:17:34  来源:igfitidea点击:

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

javascriptjqueryhtml

提问by zachu

I am trying to create a form with fields changing on fly.

我正在尝试创建一个字段更改的表单。

Start with simple text and when someone clicks on this text it transfers into editable text input field. When someone clicks away it turns back into non-editable text.

从简单的文本开始,当有人点击此文本时,它会转换为可编辑的文本输入字段。当有人点击它时,它会变回不可编辑的文本。

I gave it a go but it does not seem to work properly. Works fine on first couple of clicks but then it's loosing inputId and is mixing the buttons.

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

Here is the html

这是html

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

And here is the JavaScript (using jQuery).

这是 JavaScript(使用 jQuery)。

I am quite new in JavaScript so it may not be best quality code...

我对 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>');
        }      

    });
}

Here is live example on fiddle https://jsfiddle.net/7jz510hg/

这是小提琴的现场示例https://jsfiddle.net/7jz510hg/

I will appreciate any help as it's giving me a headache...

我将不胜感激,因为它让我头疼...

回答by Yura

First of all, you shouldn't need to use onclickin the html itself.

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

And here's another approach you might take:

这是您可能采取的另一种方法:

/**
  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>

回答by AtheistP3ace

Fiddle: https://jsfiddle.net/7jz510hg/1/

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

The issue was by not defining the inputIdWithHash and elementValue variables with var they became global variables.

问题在于没有使用 var 定义 inputIdWithHash 和 elementValue 变量,它们变成了全局变量。

var inputIdWithHash
var elementValue

Then since they had global scope the old values of them were available to the document click handler. You want them locally scoped within that turnTextIntoInputField function.

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

And an update maintaining values: https://jsfiddle.net/7jz510hg/2/

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

Side note, you are using jQuery 1.6 so I had to use unbind function instead of off.

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

Updated fiddle: https://jsfiddle.net/7jz510hg/3/

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

This uses latest jquery, event namespacing so we can attach more than one click event to the document therefore allowing us to click between the fields and not lose anything. The previous fiddle would mess up if you clicked directly on fields instead of click field, click document, click field.

这使用最新的 jquery 事件命名空间,因此我们可以将多个单击事件附加到文档,从而允许我们在字段之间单击而不会丢失任何内容。如果您直接单击字段而不是单击字段、单击文档、单击字段,则前面的小提琴会搞砸。

回答by Arjun

I suggest, don't make this complicated. I changed the text to the input field with a simple hide and show method. This is very easy to implement and understand.

我建议,不要把这复杂化。我使用简单的隐藏和显示方法将文本更改为输入字段。这很容易实现和理解。

 $('#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;">

回答by Arthur Veselov

Try this

试试这个

$('#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/

http://jsfiddle.net/yp8bt6s0/