jQuery实时获取文本区域的读数 [英] Jquery get readout of text area live

查看:103
本文介绍了jQuery实时获取文本区域的读数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否能得到一点帮助.我想实时预览其上方文本区域中的内容.

I was wondering if I could get a little help. I want to get a live preview of what is in my text area above it.

文本区域中的每一行都将以列表形式显示在其上方,因此如下所示:

Each new line in the text area will display as a list above it, so something like this:

  • 测试
  • test2
  • test3

文本区域:

test
test2
test3

我希望它的工作方式是在加载时读取文本区域的内容,并在列表中显示上方的内容.然后,当文本区域的内容更改时,它也会更改其上方的列表.

How I want it to work is that on load it reads the contents of the text area and displays the contents above in a list. Then when the contents of the text area changes it also changes the list above it.

这是我的代码: http://jsfiddle.net/spadez/9sX6X/

Here is my code: http://jsfiddle.net/spadez/9sX6X/

<h4>Placeholder</h4>
<ul id="tst"></ul>
<textarea rows="4" cols="50" placeholder="Test" id="test"></textarea>

这是我走了多远:

$('#test').bind('input propertychange', function() {
      if(this.value.length){
Rerender list to show contents
      }
});

这是我的第一个脚本,所以有人可以给我一些如何实现的指导吗?

This is one of my first scripts so could someone please give me some guidance on how this should be achieved?

推荐答案

小提琴

var list = $('#tst');

$('#test').on('keyup', function() {
      list.empty();
      if(this.value.length){
          $.each(this.value.split("\n"), function(i, val){
              list.append($('<li></li>').text(val));
          });
      }
});

$('#test').trigger('keyup'); // required to make it do the update onload

由于使用了.text(),因此可以毫无问题地处理诸如<>之类的特殊字符.还要注意,我是如何一次只选择<ul>,而不是一遍又一遍地重新选择它.

Because of my usage of .text(), this will handle special characters such as < and > without a problem. Also note how I have only selected the <ul> a single time, instead of re-selecting it over and over.

侧面说明:从jQuery 1.7开始,首选.on()代替.bind().

Side note: as of jQuery 1.7, .on() is preferred instead of .bind().

这篇关于jQuery实时获取文本区域的读数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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