如何让 JavaScript 找到焦点输入的值,如果是默认值则清除,如果是新数据则保留?

发布于 2024-11-17 22:19:16 字数 653 浏览 7 评论 0原文

我花了太多时间试图解决这个问题,并且我在 Stackoverflow 上找到了部分答案,但仍然无法解决这个问题。

我想要做的是使用一些 JS/jQuery 控制站点范围内的所有输入元素。当用户专注于输入时,如果该值与页面加载时相同,则将其清除,如果已更改,则保留它。然后在模糊时,如果该字段为空,则返回默认值。

到目前为止我所得到的是:

var input = document.getElementsByTagName('input');

$('input, textarea').focus(function() {
    value = $(this).val();

    for (var i=input.length-1; i >= 0; i--) {           
        if(value == input[i].value){
            $(this).attr("value","");   
        }   
    }
});
$('input, textarea').blur(function() {
    if($(this).val()=="") {
        $(this).val(value);
    }
});

这部分有效,它只是不断清除输入,无论它们是否已更改。我猜我存储的初始值是错误的。

I've spent too many hours trying to figure this, and I've found parts of the answer here on Stackoverflow but still can't get this working.

What I want to do is control all input elements sitewide with some JS/jQuery. When a user focuses on the input, if the value is the same as when the page loaded, clear it, if it's been altered, keep it. Then on blur, if the field is empty, return the default value.

What I have so far is this:

var input = document.getElementsByTagName('input');

$('input, textarea').focus(function() {
    value = $(this).val();

    for (var i=input.length-1; i >= 0; i--) {           
        if(value == input[i].value){
            $(this).attr("value","");   
        }   
    }
});
$('input, textarea').blur(function() {
    if($(this).val()=="") {
        $(this).val(value);
    }
});

This partly works, it just keeps clearing the inputs though, whether they have been changed or not. I'm guessing I am storing the initial values wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

瑕疵 2024-11-24 22:19:16

这条线是坏人

if(value == input[i].value){

,因为 getElementsByTagName 返回一个 HTMLCollection,对 dom 的更改也在您的输入变量中。因此,值将始终是 input[i].value,因为您获得相同输入元素的值,这当然是相同的!

使用 jquery 数据方法 保存元素内的值。在模糊时,再次检索它以进行比较。

像这样;

var handlers={
    focus: function() {
        var elm=$(this),
            value=elm.val(),
            old=elm.data("placeholder");
        if (typeof old==="undefined"){
            elm.data("placeholder", value);
            old=value;
        }
        if (old==value){
            elm.val("");
        }
    },
    blur:function() {
        var elm=$(this);
        if( elm.val() == "" ) {
            elm.val( elm.data("placeholder") );
        }
    }
};
$('input, textarea').each(function(i, elem){
    $(elem).
        focus(handlers.focus).
        blur(handlers.blur);
});
//not tested, should work!

this line is the bad guy

if(value == input[i].value){

since getElementsByTagName returns a HTMLCollection, changes to the dom are also in your input variable. Thus, value will always be input[i].value, since your getting the value of the same input elem, which of course are the same!

use jquery data method to save the value within the element. and on blur, retrieve it again to make the comparison.

like this;

var handlers={
    focus: function() {
        var elm=$(this),
            value=elm.val(),
            old=elm.data("placeholder");
        if (typeof old==="undefined"){
            elm.data("placeholder", value);
            old=value;
        }
        if (old==value){
            elm.val("");
        }
    },
    blur:function() {
        var elm=$(this);
        if( elm.val() == "" ) {
            elm.val( elm.data("placeholder") );
        }
    }
};
$('input, textarea').each(function(i, elem){
    $(elem).
        focus(handlers.focus).
        blur(handlers.blur);
});
//not tested, should work!
静待花开 2024-11-24 22:19:16

您只需要先存储一个默认值,然后在模糊和聚焦时引用它。

$('input, textarea').each(function() {
        var $this = $(this);
        $this.data('defaultValue', $this.val()); // stores the default value

        $this.focus( function() {
            if ($this.val() == $this.data('defaultValue')) { 
                $this.val(""); 
            }
        });

        $this.blur( function() {
            if ($this.val() == "") { 
                $this.val( $this.data('defaultValue') ); 
            }
        });
});

再看一遍,我认为我们甚至不需要数据存储。

$('input, textarea').each(function() {
        var $this = $(this),
            defaultValue = $this.val(); // stores the default value

        $this.focus( function() {
            if ($this.val() == defaultValue) { 
                $this.val(""); 
            }
        });

        $this.blur( function() {
            if ($this.val() == "") { 
                $this.val(defaultValue); 
            }
        });
});

You just need to store a default value first, then reference it on blur and focus.

$('input, textarea').each(function() {
        var $this = $(this);
        $this.data('defaultValue', $this.val()); // stores the default value

        $this.focus( function() {
            if ($this.val() == $this.data('defaultValue')) { 
                $this.val(""); 
            }
        });

        $this.blur( function() {
            if ($this.val() == "") { 
                $this.val( $this.data('defaultValue') ); 
            }
        });
});

With a second look, I think that we don't even need the data store.

$('input, textarea').each(function() {
        var $this = $(this),
            defaultValue = $this.val(); // stores the default value

        $this.focus( function() {
            if ($this.val() == defaultValue) { 
                $this.val(""); 
            }
        });

        $this.blur( function() {
            if ($this.val() == "") { 
                $this.val(defaultValue); 
            }
        });
});
依 靠 2024-11-24 22:19:16

这是我在搜索框中使用的:

this what I use on my Search box:

<input name="q" value="Search here ..." onfocus="if(this.value == 'Search here ...') this.value = '';" onblur="if(this.value == '') this.value = 'Search here ...';">

忆沫 2024-11-24 22:19:16

我认为 @japrescott 是正确的,但你还有另一个问题 - 在块中:

$('input, textarea').blur(function() {
    if($(this).val()=="") {
        $(this).val(value);
    }
});

...变量 value 未在范围内定义。

I think @japrescott is correct, but you have another issue as well - in the block:

$('input, textarea').blur(function() {
    if($(this).val()=="") {
        $(this).val(value);
    }
});

...the variable value isn't defined in scope.

书间行客 2024-11-24 22:19:16

因此,问题 1 - 输入中的集合是通过引用的,因此当您的输入更新时,它们也会在集合中更新,因此该值始终显示为默认值。

我建议不要以这种方式存储默认值,而是将它们存储为元素的一部分。加载时,您可以循环遍历元素并将值添加到“默认”属性。您还可以在服务器端添加默认属性,这样会更好。

像这样:

<input type='text' default='myval' value='myval'/>
var jInput = $('input');
if(jInput.val() == jInput.attr('default'))
...

我相信你明白了。

So, issue 1 - that collection in input is by reference, so when your inputs are updated, they are also are updated in the collection, thus the value always appears to be the default.

What I would recommend is rather than storing the default values that way, store them as part of the element. On load you can loop through the elements and add the values to a "default" attribute. You could also add the default attribute server-side which would be better.

Something like this:

<input type='text' default='myval' value='myval'/>
var jInput = $('input');
if(jInput.val() == jInput.attr('default'))
...

I'm sure you get the idea.

圈圈圆圆圈圈 2024-11-24 22:19:16

这一切都完成了: http://jsfiddle.net/uUzY3/4/

$(function() {
    $("input").each( function () {
        $(this).data('initialValue', $(this).val());
    }).bind('focus', function() {
        if ($(this).val() == $(this).data('initialValue'))
            $(this).val("");
    });
});

this does it all: http://jsfiddle.net/uUzY3/4/

$(function() {
    $("input").each( function () {
        $(this).data('initialValue', $(this).val());
    }).bind('focus', function() {
        if ($(this).val() == $(this).data('initialValue'))
            $(this).val("");
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文