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

zac*_*chu 11 html javascript jquery

我正在尝试创建一个表单,其中字段会在飞行中更改.

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

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

这是html

<p id="firstElement" onclick="turnTextIntoInputField('firstElement');">First Element</p>
<p id="secondElement" onclick="turnTextIntoInputField('secondElement');">Second Element</p>
Run Code Online (Sandbox Code Playgroud)

这是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>');
        }      

    });
}
Run Code Online (Sandbox Code Playgroud)

以下是小提琴的实时示例https://jsfiddle.net/7jz510hg/

我会感激任何帮助因为它让我头疼...

Yur*_*ura 28

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

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

/**
  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();
  
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 如果我今天有选票,我会投票支持你.它比我的回答更好.虽然诚实地说我并没有试图重新发明他正在做的事情,但只要解决他所遇到的问题并告诉他为什么会这样. (2认同)