jQuery在单独的div中将用户输入反映为类型 [英] jQuery to reflect user input as the type, in a separate div

查看:127
本文介绍了jQuery在单独的div中将用户输入反映为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为names的文本框,允许用户输入各个单词,每个单词之间用空格分隔.

然后我有一个divpreview,最初不包含任何内容,但是每个字符都出现在names文本框中,我想在预览div中显示每个单独的单词(基于在空格"分隔符上)作为单独的跨度标签输出(这样我就可以将样式应用于预览中的每个单独的名称".

我还应该提到,在某些情况下,值将通过jQuery UI自动完成列表(我已经开始使用)到达names文本框中,并且也要预先填充(当我编辑例如进行记录,并使用先前选择的名称预填充文本框.

我的jQuery不好用,我一直在寻找解决方案,但没有取得太大的成功.

我将如何实现这一目标?

解决方案

除非性能成为问题,否则我只会从names文本框中获取所有文本,并在每次击键时将其填充到预览div中.

$('#names').bind('keyup', function(){
    var text = $(this).val();
    var tokens = text.split(" ");
    var output = "";
    for(int i=0; i<tokens.length; i++){
       output+= "<span>"+tokens[i]+"</span>&nbps;"; //note extra space at the end
    }
    $('#preview').innerHTML=output;
});

I have a textbox called names that allows a user to enter individual words, each word separated by a space.

I then have a div called preview which contains nothing initially, but with each character that appears in the names textbox, I'd like to show this in the preview div, with each individual word (based on 'space' seperation) to be output as individual span tags (so I can then apply a style to each individual 'name' within the preview.

I should also mention that in some scenarios, values will be arriving in the names textbox via a jQuery UI Autocomplete list (which I've already got working), and also pre-filled (when I'm editing a record for example and prefill the textbox with previously chosen names).

My jQuery isn't great and I've had a look around for a solution, but not had much success.

How would I go about achieving this?

解决方案

I would just take all the text from the names textbox and populate it in the preview div at each key-stroke unless performance becomes an issues.

$('#names').bind('keyup', function(){
    var text = $(this).val();
    var tokens = text.split(" ");
    var output = "";
    for(int i=0; i<tokens.length; i++){
       output+= "<span>"+tokens[i]+"</span>&nbps;"; //note extra space at the end
    }
    $('#preview').innerHTML=output;
});

这篇关于jQuery在单独的div中将用户输入反映为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆