【问题标题】:Turn text field into input field and back again将文本字段转换为输入字段并再次返回
【发布时间】:2016-04-02 21:05:36
【问题描述】:

所以我试图让它每次你点击一个文本字段时,它都会变成一个输入字段,然后你输入你想要的任何内容,点击输入,它会变成一个文本字段,然后这个过程就开始了重新来过。我能够让它运行,但只有一次。我怎样才能让它运行多次,以便我可以不断更改文本值?

<p class="text">Text</p>

$(".text").click(function() {
  $(this).replaceWith("<input type='text' class='text'>");
  $(".text").select();

  $(".text").keypress(function(e) {
    if (e.which == 13) {
      var textVal = $(".text").val();
      $(".text").replaceWith("<p class='text'>" + textVal + "</p>");
    }
  });

});

【问题讨论】:

    标签: javascript jquery text input


    【解决方案1】:

    我觉得会更好

    $(function() {
        $(".text").live("click", function() {
            // alert(7);
            $(this).replaceWith("<input type='text'/>");
    
            $("input").live("blur", function() {
                var textVal = $("input").val();
                $("input").replaceWith("<p class='text'>" + textVal + "</p>");
            });
        });
    });
    

    【讨论】:

    • 尝试添加一些解释以更好地改进您的答案
    • 不用担心。我们来这里学习。我们不仅学习编程知识,还学习如何有效沟通。试一试:)
    • 我今年刚接触编程,但是我的英语很差
    • 没关系。一切顺利! :D
    【解决方案2】:

    我想通了。代码如下:

    <p class="text">Text</p>
    
    function changeText() {
      $(".text").click(function() {
        $(this).replaceWith("<input type='text' class='text'>");
        $(".text").select();
    
        $(".text").keypress(function(e) {
          if (e.which == 13) {
            var textVal = $(".text").val();
            $(".text").replaceWith("<p class='text'>" + textVal + "</p>");
            changeText();
          }
        });
    
      });
    }
    
    changeText();
    

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 1970-01-01
      • 2015-01-19
      • 2013-02-18
      • 2011-10-30
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      相关资源
      最近更新 更多