【问题标题】:Append text onto html text input while typing键入时将文本附加到 html 文本输入中
【发布时间】:2013-06-21 15:22:08
【问题描述】:

我想在用户输入时使用 jquery 将文本附加到用户在文本框中输入的内容。

假设我想在用户键入的内容末尾附加“是一顶帽子”。

假设用户开始在字段中输入“我的朋友”。

当他们键入时,框会显示:

M -> M is a hat
y -> My is a hat
  -> My  is a hat
F -> My F is a hat
r -> My Fr is a hat
...

我开始为按键事件编写一个函数,但后来我意识到我最终会得到类似的东西

M -> M is a hat
y -> M is a haty is a hat
...

所以我想知道我应该怎么做

  1. 替换旧后缀
  2. 将光标放回用户输入的位置
  3. 确保他们只能在后缀之前输入,因此他们无法编辑后缀

【问题讨论】:

    标签: jquery forms


    【解决方案1】:

    您可以像这样附加到span

    var phrase = " is a hat";
    $("#idOfInput").keydown(function() {
        $("#idOfSpan").html(this.value + phrase);
    });
    

    【讨论】:

      【解决方案2】:

      你可以试试这个

      JS

      $("input").keyup(function() {
          $(".dynamic").html(this.value);
      });
      

      HTML

      <input type="text" />
      <div>
          <span class="dynamic"></span>
          <span class="static"> is a hat </span>
      </div>
      

      Check Fiddle

      您将基本上定位保存动态文本的跨度并根据 keyup 事件呈现 html。

      【讨论】:

      • 我拿了 tyme's 只是因为他的做法不同,但是 +1 为小提琴。
      【解决方案3】:
      this following example work perfectly .  
       **html**
      
          <input type="text" id="text"/>
          <p><span id="app"></span>
          <span>this is a hat</span>
          <p>
      
          **script**
          ----------
          $("#text").keyup(function(){
              $("#app").text($("input").val());
          });
      

      【讨论】:

        猜你喜欢
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多