2

我想在用户输入时使用 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. 确保他们只能在后缀之前输入,因此他们无法编辑后缀
4

3 回答 3

3

您可以span像这样附加:

var phrase = " is a hat";
$("#idOfInput").keydown(function() {
    $("#idOfSpan").html(this.value + phrase);
});
于 2013-06-24T23:53:08.980 回答
3

你可以试试这个

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>

检查小提琴

您基本上将定位包含动态文本的跨度并基于 keyup 事件呈现 html。

于 2013-06-24T23:56:48.657 回答
0
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());
    });
于 2013-06-25T07:07:41.790 回答