我有一个表单,我想在填写表格后立即动态显示表单的某些元素.
想象一下,如果我的名字有文字输入.在您输入时,我还希望您的姓名出现在网页的其他部分.
我将如何以最简单的方式实现这一目标?
(请参阅下面的更新,我后来意识到我完全忘记使用鼠标操作将文本粘贴到字段中.)
您可以挂钩的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 || "??";
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用DOM0风格的事件处理程序("onXyz"属性,我通常不喜欢)的一个非常基本的例子.执行这些操作的最简单方法是使用jQuery,Prototype,YUI,Closure或其他任何库中的库.它们将为您平滑浏览器差异,让您专注于您实际尝试的内容.
以上是使用jQuery的内容:
$('#nameField').bind('keydown keyup keypress', function() {
$('#nameDisplay').html(this.value || "??");
});
Run Code Online (Sandbox Code Playgroud)
更新:实际上,上面会遗漏使用鼠标粘贴到现场的事情.你认为change处理程序对此有好处,但它不一定会在焦点离开字段之前触发,所以使用这样的定时进程并不罕见:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
你要避免为每个字段单独使用这些字段(相反,为所有字段使用单个计时器),你需要根据实际需要调整计时器 - 对以下事实敏感:你正在这样做,你正在消耗资源.如果你想在某个阶段停止检查(这是个好主意),请保存以下的返回值setInterval:
var timerHandle = setInterval(updateNameDisplay, 100);
Run Code Online (Sandbox Code Playgroud)
...并像这样停止循环:
clearInterval(timerHandle);
timerHandle = 0;
Run Code Online (Sandbox Code Playgroud)
这是动态观看字段的更完整示例,仅在字段具有焦点时使用计时器.我已经在这个例子中使用了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);
}
});?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21704 次 |
| 最近记录: |