使用javascript onclick替换任何html标签以进行输入

时间:2017-03-26 20:10:14

标签: javascript jquery html

我正在尝试将html标签替换为使用javascript输入 如果按下标签,则转为输入

示例:

<a href="#">text</a> 

替换为:

<input value="text" />

或:

<h2 href="#">text</h2> 

替换为:

<input value="text" />

这是代码:

/**
  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>
  
 <a data-editable class="navbar-brand" href="#page-top">Second Element</a>
<p>Not editable</p>

问题是:我的课程已删除,也不是已创建“p”而非“a”或“h2”或其他任何内容的标签

2 个答案:

答案 0 :(得分:2)

你想制作同样的标签吗?

如果能够理解的话会有效:

$('body').on('click', '[data-editable]', function(){
  
  var $el = $(this);
              
  var $input = $('<input/>').val( $el.text() );
  $el.replaceWith( $input );
  $input.focus();
  var save = function(){
    $el.text($input.val());
    $input.replaceWith( $el );
  };
  
  $input.one('blur', save);
  
});
.how { color: red}
.green { color: lime}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="how" data-editable>First Element</p>
  
 
<a href="#" data-editable>Second Element</a>
<h2 class="green" data-editable>Second Element</h2>

<p>Not editable</p>

答案 1 :(得分:1)

如果我理解了你的目标,请查看

Example

代码:

$("body").on("click","[data-editable]", function() {
  var $el = $(this);
  var $input = $("<input/>").val($el.text()).addClass($el.attr('class')).data("tagName", this.outerHTML);
  $el.replaceWith($input);
  console.log($input.data()["tagName"]);
   var save = function(){
    var $p = $($input.data()["tagName"]).text( $input.val() ).addClass($input.attr("class"));
    $input.replaceWith( $p );
  };

  $input.one('blur', save).focus();
})

我刚刚保存了点击的元素类和html,所以当我们重新创建它时,它会作为前一个元素而不是静态p标签出现。