回到浏览器时,如何通过jquery删除一些输入文本?

我有以下页面的一些错误: http : //jsbin.com/agedu/源代码和一些评论: http : //jsbin.com/agedu/edit

问题是当输入内容并进行查询以显示搜索结果时,如果我回到浏览器中的搜索页面(Firefox 3.5,但与IE8相同),则不再有我的搜索条件了。

它被灰色文本取代。 这个灰色文本,我只想在没有任何填充文本时拥有。

当我删除jQuery代码时,如果我进行一些搜索并按下浏览器上的“返回”按钮,则填充的文本仍然存在。

即使有这个示例页面: http : //mucur.name/system/jquery_example/

如果我写了一些文本,在地址栏中加载一些其他URL,然后按回车键,填充的文本仍然存在,而不是我的代码。

所以我的问题是:你知道如果填写这个文本怎么保留?

应该有一种方法来检测输入是否已填满,如果是,则避免替换文本。

它可能来自浏览器以及它们如何处理JavaScript,但我不确定。

哇,调试这个花了很长时间,我认为你应该使用val方法而不是使用’value’属性。

无论如何,有问题的是这个

$(this).attr('value', hvalue).addClass(opts.hclass).unbind('focus blur').bind('focus', 

在上面的行中,当您指定属性“value”时,实际上是在更改文本框的值。 只有在非空时才应更改它。

我改变了你的代码,到处使用val()方法,它按预期工作。

工作演示: http : //jsbin.com/ihegu/

[注意当您在Google上搜索某些内容并单击后退按钮时,演示如何正确地显示“维基百科”文本。

  (function($) { $.fn.inputdynvalue = function(options) { var opts = $.extend({}, $.fn.inputdynvalue.defaults, options); return this.each(function() { var hvalue = opts.htext; switch (opts.htext) { case 'title': hvalue = $(this).attr('title'); break; case 'value': hvalue = $(this).val(); break; } //Modify the text value ONLY if it's non empty. if($(this).val() === '') { $(this).val(hvalue); } //If title and value is same, apply the grey text class. if($(this).val() === this.title) { $(this).addClass(opts.hclass); //Why do you unbind the event? }; $(this).bind('focus', function() { if ($(this).val() === this.title) { $(this).val(''); $(this).removeClass(opts.hclass); } }); $(this).bind('blur', function() { if ($(this).val() === '') { $(this).val(this.title); $(this).addClass(opts.hclass); } }); }); }; $.fn.inputdynvalue.defaults = { htext: 'title', hclass: 'hint' }; })(jQuery); $(document).ready(function() { $("input[type='text']").inputdynvalue(); }); 

当您初始化插件时,您正在设置重置输入的值,我只是重构了一点并添加了以下检查:

  if (this.value === '' || this.value === hvalue){ $(this).attr('value', hvalue).addClass(opts.hclass); } 

我将这些操作与焦点事件连接链分开。

现在它只会设置默认值(hvalue)和默认灰色类(hclass), 如果元素值为''或者它具有默认值

在这里查看您的代码段。

在IE8和FF中测试过

这是从源复制并修改的。

我在一段时间内用简单的旧js制作了一个幻影文本控件,在jQuery中查看它让我想回去重写它。

        Test   

inputdynvalue()函数在调用时显式强制文本框文本,即使文本框非空。

像这样修复它:

  (function($) { $.fn.inputdynvalue = function(options) { var opts = $.extend({}, $.fn.inputdynvalue.defaults, options); return this.each(function() { var hvalue = opts.htext; switch (opts.htext) { case 'title': hvalue = $(this).attr('title'); break; case 'value': hvalue = $(this).attr('value'); break; } if (this.value === '') { $(this).attr('value', hvalue).addClass(opts.hclass) } $(this).unbind('focus blur').bind('focus', function() { if (this.value === this.title) { this.value = ''; $(this).removeClass(opts.hclass); } }).bind('blur', function() { if (this.value === '') { this.value = this.title; $(this).addClass(opts.hclass); } }); }); }; $.fn.inputdynvalue.defaults = { htext: 'title', hclass: 'hint' }; })(jQuery); 

关键是线条:

  if (this.value === '') { $(this).attr('value', hvalue).addClass(opts.hclass) } 

从之前替换非条件覆盖。

固定版本可以在http://jsbin.com/ikipi上看到。