设置HTML文本输入框的“默认”值。单击ESC时还原该值 [英] Setting an HTML text input box's "default" value. Revert the value when clicking ESC

查看:161
本文介绍了设置HTML文本输入框的“默认”值。单击ESC时还原该值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当网页表单写入浏览器时,浏览器会记住文本INPUT框的初始值。即。当它收到这样的HTML:

 < input type =textvalue =something> 

浏览器会记住something作为初始值/默认值。当用户开始输入时,然后点击ESC,浏览器将字段恢复为初始值(如果它最初是空白的,则为空)。



然而,当以编程方式创建一个文本输入框时,点击ESC始终会使该框空白,即使我使用默认值创建它也是如此:

  $('< input type =textvalue =something>')



<浏览器不会将其计为默认值,并且在按ESC时不会恢复为该值。所以我的问题是,有没有办法在代码中创建一个文本框,并以某种方式为它分配一个默认值,所以ESC键的工作方式就好像浏览器在HTML文档中收到它一样?

esc 行为仅仅是IE浏览器的方式。

  var element = document.createElement('input')使用jQuery来创建元素, ); 
element.type ='text';
element.value = 100;
document.getElementsByTagName('body')[0] .appendChild(element);

http:// jsfiddle.net/gGrf9/



如果您想将此功能扩展到其他浏览器,那么我会使用jQuery的数据对象来存储默认值。

  //在页面上存储所有元素的默认值。设置新的默认模糊
$('input')。each(function(){
$(this).data('default',$(this).val());
$(this).blur(function(){$(this).data('default',$(this).val());});
});
$ b $('input')。keyup(function(e){
if(e.keyCode == 27){$(this).val($(this).data 'default'));}
});


When a web form is written to the browser, the browsers remembers what the initial values are of a text INPUT box. ie. when it receives HTML like this:

<input type="text" value="something">

The browser remembers "something" as the initial/default value. When the user starts typing over it, then hits ESC, the browser reverts the field to the initial value (or blank if it was initially blank of course).

However, when creating a text input box programatically, hitting ESC always seems to blank the box, even if I create it with a default value like so:

$('<input type="text" value="something">')

The browser doesn't count this as a default value and doesn't revert to it when hitting ESC. So my question is, is there a way to create a text box in code and somehow assign it a default value, so the ESC key works as if the browser received it in the HTML document?

解决方案

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

这篇关于设置HTML文本输入框的“默认”值。单击ESC时还原该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆