jQuery设置input.value = input.title(或其他输入属性)

Tim*_*key 0 javascript forms jquery this

我试图找出如何在页面加载时将input文本字段的值设置为它的值title,作为显示占位符文本的方法.我正在使用HTML4 Strict doctype.我不想将占位符文本存储在输入值中,因为我不希望没有javascript的人在键入之前删除文本.我想用javascript添加它,然后在输入获得焦点时删除.我有focus()blur()方法工作,但我无法弄清楚如何编写初始页面加载函数将输入的标题传递给val()函数.

我目前有这个代码:

// This doesn't work, it grabs the page title:
$('#item-search').val(this.title);

// Works:
$('#item-search').focus(function() {
    if (this.value == this.title) {
        this.value = '';
    } 
});

// Works: 
$('#item-search').blur(function() {
    if (this.value == '') {
        this.value = this.title;
    } 
});
Run Code Online (Sandbox Code Playgroud)

kap*_*apa 5

只是要添加另一个变体,.val()可以接受函数作为其参数,修复您的this问题:

$('#item-search').val(function () {
    return this.title;
});
Run Code Online (Sandbox Code Playgroud)