问题
I want to take the information typed into a text field and display it in a paragraph elsewhere on the page. Basically, exactly what is happening below as I'm type this (go to post a question and start typing in the main text box and you'll see what I mean).
Any idea how to do this? The page has so much JavaScript on it I can't find how they did it.
回答1:
I think you are looking for this.
Here is how your html should look like:
<textarea id="txt" style="width:600px; height:200px;"></textarea>
<p id="preview"></p>
And jQuery:
$(function(){
$('#txt').keyup(function(){
$('#preview').text($(this).val());
});
});
This grabs the value of textarea
on its keyup
event and later the paragraph's text is changed (text()
method) with that of textarea
$(this).val()
.
回答2:
Here's an example that should just work -
<html>
<head>
<style>
#typing{background-color:;}
#display{background-color:#FFEFC6;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>
<body>
<div id="typing">
<input type="text" name="typing" value="" id="typing_input" style="height:100px;width:300px;">
</input>
</div>
<div id="display">
<p id="typing_display"></p>
</div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$('#typing_input').bind("keypress keydown", function(event) {
$('#typing_display').text($('#typing_input').attr("value"));
});
});
</script>
</body>
</html>
Sorry for the extra styles - can't help myself. Jquery's .change() won't change is until different events are fired, .live() and .bind() are what you want. There's also the .attr("value") part which sometimes does extra magic that i don't totally understand - but it does stay up to date. Best of luck!
回答3:
I would use something like keyup and update the display each time a key is released. You might also need to handle the change event in case someone pastes something into the box.
<div id="container">
<textarea id="textfield"></textarea>
<p id="displayArea"></p>
</div>
<script type="text/javascript">
var display = $('#displayArea');
$('#textfield').keyup( function() {
display.text( $(this).val() );
}).change( function() {
display.text( $(this).val() );
});
</script>
Also, you could look at the WMD editor, which is what SO uses. It does more than you are asking for, but you could get some ideas from it.
来源:https://stackoverflow.com/questions/3441699/change-paragraph-text-dynamically-with-jquery