使用jQuery将输入框标题设置为值

Nyx*_*nyx 2 html javascript css forms jquery

我正在创建输入文本框,在页面加载时将其title属性设置为其值.当用户单击文本框时,其值将被清除,当文本框失去焦点时,用户输入的值将保留,或者默认值将取代.

问题:我似乎无法在页面加载时设置文本框的值.虽然改变焦点和模糊的值很有效.怎么了?

jQuery代码

$(function() {
    ///////////////////
    // Register Form //
    ///////////////////
    $(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
    $(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');

    $(".splash_register_short_input, .splash_register_long_input").focus(function() {
        if (this.value == $(this).attr('title')) {
            this.value = '';
        }
    });

    $(".splash_register_short_input, .splash_register_long_input").blur(function() {
        if (this.value == '') {
            this.value = $(this).attr('title');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

HTML代码

<div id="splash_register_form">
    <input type="text" name="register_first_name" class="splash_register_short_input" title="First Name" />
    <input type="text" name="register_last_name" class="splash_register_short_input" title="Last Name" />
    <input type="text" name="register_email" class="splash_register_long_input" title="Email" />
    <input type="text" name="register_password" class="splash_register_long_input" title="Password" />
</div>
Run Code Online (Sandbox Code Playgroud)

Jam*_*ill 5

您正在尝试.value在jQuery对象上设置不存在的属性().请$("[YourSelector]").val()改用.

改变这个:

$(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
$(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');
Run Code Online (Sandbox Code Playgroud)

对此:

$(".splash_register_short_input, .splash_register_long_input").val($(this).attr('title'));
$(".splash_register_short_input, .splash_register_long_input").val($(".splash_register_short_input, .splash_register_long_input").attr('title'));
Run Code Online (Sandbox Code Playgroud)