jQuery实时获取文本区域的读数

编程入门 行业动态 更新时间:2024-10-27 20:24:43
本文介绍了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.

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

Here is my code: jsfiddle/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实时获取文本区域的读数

本文发布于:2023-11-10 00:28:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573858.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:读数   实时   文本   区域   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!