使用 Javascript 动态显示输入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4790946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically displaying input values using Javascript
提问by AKor
I have a form, and I want to dynamically display certain elements of the form as soon as they are filled out.
我有一个表单,我想在填写完表单的某些元素后立即动态显示它们。
Imagine if I had a text input for your name. As you type, I also want your name to appear in a different part of the webpage.
想象一下,如果我有一个文本输入你的名字。在您键入时,我还希望您的名字出现在网页的不同部分。
How would I accomplish this in the simplest manner?
我将如何以最简单的方式完成此操作?
回答by T.J. Crowder
(See below for an update, I realized later I'd completely forgotten to handle pasting text into the field using a mouse action.)
(请参阅下面的更新,我后来意识到我完全忘记了使用鼠标操作将文本粘贴到字段中。)
You can hook the keypress
event (you'll probably want keydown
and keyup
as well) on the text input field and use it to trigger an update of a DOM element elsewhere. For instance:
您可以挂钩的keypress
事件(你可能会希望keydown
和keyup
对文本输入字段为好),并用它在其他地方引发DOM元素的更新。例如:
var nameField = document.getElementById('nameField');
nameField.onkeydown = updateNameDisplay;
nameField.onkeyup = updateNameDisplay;
nameField.onkeypress = updateNameDisplay;
function updateNameDisplay() {
document.getElementById('nameDisplay').innerHTML = this.value || "??";
}
That's a very basic example using a DOM0-style event handler (the "onXyz" property, which I don't normally like). The simplestway to do these things is to use a library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser differences for you and let you focus on what you're actually trying to do.
这是一个使用 DOM0 样式事件处理程序(我通常不喜欢的“onXyz”属性)的非常基本的示例。做这些事情的最简单的方法是使用一个库,比如jQuery、Prototype、YUI、Closure或其他几个库中的任何一个。它们会为您消除浏览器差异,让您专注于实际尝试做的事情。
Here's the above using jQuery:
这是上面使用jQuery的:
$('#nameField').bind('keydown keyup keypress', function() {
$('#nameDisplay').html(this.value || "??");
});
Update: Actually, the above will miss things like pasting into the field using the mouse. You'd think a change
handler would be good for this, but it doesn't necessarily fire until focus leaves the field, so it's not uncommon to use a timed process like this:
更新:实际上,上面的内容会遗漏诸如使用鼠标粘贴到字段中的内容。您会认为change
处理程序对此有好处,但它不一定会在焦点离开该字段之前触发,因此使用这样的定时过程并不少见:
JavaScript, no library:
JavaScript,没有库:
var nameField = document.getElementById('nameField');
var lastNameValue = undefined;
updateNameDisplay();
setInterval(updateNameDisplay, 100);
function updateNameDisplay() {
var thisValue = nameField.value || "??";
if (lastNameValue != thisValue) {
document.getElementById('nameDisplay').innerHTML = lastNameValue = thisValue;
}
}
You'll want to avoid having a separate one of these for each field (instead, use a single timer for all of them) and you'll want to adjust the timer according to what you actually need — be sensitive to the fact that when you're doing this, you're consuming resources. If you'll want to stop the check at some stage (and it's a good idea), save the return value from setInterval
:
您将希望避免为每个字段使用单独的其中一个(相反,对所有字段使用一个计时器),并且您希望根据您的实际需要调整计时器 - 对以下事实保持敏感你这样做,你正在消耗资源。如果您想在某个阶段停止检查(这是一个好主意),请从setInterval
以下位置保存返回值:
var timerHandle = setInterval(updateNameDisplay, 100);
...and stop the loop like this:
...并像这样停止循环:
clearInterval(timerHandle);
timerHandle = 0;
Here's a more complete example of dynamically watching fields, only using the timer when a field has focus. I've used jQuery for this example because it simplifies it and you did ask for simple (if you use another library or don't use any library, you can probably port this easily enough; the main place jQuery is useful in this case is in finding the inputs within the form):
这是动态观察字段的更完整示例,仅在字段具有焦点时使用计时器。我在这个例子中使用了 jQuery,因为它简化了它并且你确实要求简单(如果你使用另一个库或不使用任何库,你可以很容易地移植它;在这种情况下 jQuery 有用的主要地方是在查找表单中的输入时):
jQuery(function($) {
var formTimer = 0,
currentField,
lastValue;
updateWatchingIndicator();
$('#theForm :input')
.focus(startWatching)
.blur(stopWatching)
.keypress(updateCurrentField);
function startWatching() {
stopWatching();
currentField = this;
lastValue = undefined;
formTimer = setInterval(updateCurrentField, 100);
updateWatchingIndicator();
}
function stopWatching() {
if (formTimer != 0) {
clearInterval(formTimer);
formTimer = 0;
}
currentField = undefined;
lastValue = undefined;
updateWatchingIndicator();
}
function updateCurrentField() {
var thisValue;
if (currentField && currentField.name) {
thisValue = currentField.value || "??";
if (thisValue != lastValue) {
lastValue = thisValue;
$('#' + currentField.name + 'Display').html(thisValue);
}
}
}
function updateWatchingIndicator() {
var msg;
if (currentField) {
msg = "(Watching, field = " + currentField.name + ")";
}
else {
msg = "(Not watching)";
}
$('#watchingIndicator').html(msg);
}
});?
回答by Endophage
Use javascript's onkeypress event. Check this w3schools pageabout it. You can then use it to call a function that will update the dom element where you want to display the item. Should go something like this:
使用 javascript 的 onkeypress 事件。检查这个w3schools 页面。然后,您可以使用它来调用一个函数,该函数将更新要在其中显示项目的 dom 元素。应该是这样的:
<script type="text/javascript">
function update(element)
{
document.getElementById("dynamic_name").innerHTML = element.value;
}
</script>
<input type="text" onkeypress="update(this)" />
<div id="dynamic_name"></div>
You can obviously rename elements and move them around but this is the general concept.
您显然可以重命名元素并移动它们,但这是一般概念。
回答by Stefanos Chrs
A very simple and elegant solution could be to use AngularJS:
一个非常简单而优雅的解决方案可能是使用 AngularJS:
<input type='text' ng-model='userText'/>
<p ng-bind='userText'></p>