I'm making a post page for my website, and I would like to add an auto update preview box, showing what is being typed into the text box above. Obviously i'd like to use javascript, or jquery. And the thing I need is basically the same thing as on the ask page for this website!
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Are you looking for .keyup()
?
Look at this fiddle for a simple example: http://jsfiddle.net/LUDWQ/2/
$('#tb1').keyup(function() {
$('#tb2').val($('#tb1').val());
});
When putting in into a div
and not another textbox you can use this:
$('#tb1').keyup(function() {
$('#tb2').html($('#tb1').val()); //tb2 is a <div> here
});
Fiddle: http://jsfiddle.net/LUDWQ/4/
回答2:
If the textarea control has an id of "textarea_control" and the preview div/span/whatever has an id of "preview", you could potentially use something like this (snagged from some code I used in a project and tweaked for your example).
//Wait for input in textarea
$("#textarea_control").keyup(function() {
var inputB = $(this).val();
if(globalTimeout != null){
clearTimeout(globalTimeout);
}
//Give the user a slight time to delay while typing
globalTimeout = setTimeout(function(){
$("#preview").html(inputB);
}, 1000);
Hope this helps!
Please note, this does not do any filtering of user's input, so you should probably think about calling a separate function to filter the data to prevent injection or other attacks before displaying the preview.