繁体   English   中英

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

[英]Using jQuery to set input box title to value

我正在创建输入文本框,该文本框将在加载页面时将其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');
        }
    });
});

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>

您正在尝试设置jQuery对象上不存在的属性( .value )。 使用$("[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');

对此:

$(".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'));

我认为我们需要在这里枚举.each函数应用于为每个文本框分配值,例如

    $(".splash_register_short_input, .splash_register_long_input").each(function(){
     $(this).val($(this).attr('title'));
    });

这样的事情应该工作:

$(document).ready(function(){ 
  $('input[type=text]').focus(function(){ 
    if($(this).val() == $(this).attr('title'))
    {
      $(this).val('');
    }
  });

  $('input[type=text]').blur(function(){
    if($(this).val() == '')
    {
      $(this).val($(this).attr('title'));
    } 
  });
}); 

但是,您也可以搜索有关“ placeholder”的jQuery插件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM