JQuery 焦点/模糊事件帮助

发布于 2024-08-07 19:00:57 字数 392 浏览 3 评论 0原文

$(document).ready(function() {

    $('#username').focus(function() {
        $(this).val('');
    })
    $('#username').blur(function() {
        var l = $(this).val.length;
        if (l == 0) {
            $(this).val('Username');
        }
    })

});

上面的代码应该做的是在聚焦时清空 #username 输入字段的值,并在失去焦点时填写用户友好的“用户名”,以防它仍然为空。

但第二部分不起作用(我认为我使用的 if 条件存在一些问题?)。

$(document).ready(function() {

    $('#username').focus(function() {
        $(this).val('');
    })
    $('#username').blur(function() {
        var l = $(this).val.length;
        if (l == 0) {
            $(this).val('Username');
        }
    })

});

What the above code is supposed to do is empty the value of #username input field when focused and fill in the user friendly "Username" there when it loses focus in case it's still empty.

The second part doesn't work though (I think there is some problem with the if condition I'm using?).

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

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

发布评论

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

评论(2

蔚蓝源自深海 2024-08-14 19:00:57

对于模糊函数的第二行,尝试

var l = $(this).val().length;

另外,尝试警告该值以查看是否正常。

For the second line of your blur function try

var l = $(this).val().length;

Also, try alerting this value to see if it is finding it okay.

亚希 2024-08-14 19:00:57

使用 $(this).val().length 代替。 $(this).val 仅引用该函数。以及函数的length 属性 是预期参数的数量,而不是该函数返回值的长度。

Use $(this).val().length instead. $(this).val only references the function. And the length attribute of a function is the number of expected arguments and not the length of the return value of that function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文