0

我有多个这样的文本框。我想在获得焦点时将文本应用于模糊和空白。我可以为单个文本框实现这一点。如何传递当前元素 id 而不是在 JavaScript 函数中硬编码“#name”值?

$(document).ready(function(){


    $('#Name').focus(function()
    {
         var $ele = $(this).attr('id');
            $(this).val('');
            $(this).css('color', '#000000');
    });

    $('#Name').blur(function()
    {
           var $ele = $(this).attr('id');
            $(this).val($ele);
            $(this).css('color', '#a9a9a9')
    });
});



<input id="Name" type="text" value="" name="Name">
<input id="Phone" type="text" value="" name="Phone" >
<input id="Email" type="text" value="" name="Email">
4

5 回答 5

2

您可以选择所有输入,您可以使用;$('input')放置过滤器文本输入 [type="text"]您可以利用 jQuery 链接。

$(document).ready(function(){   

    $('input[type="text"]').focus(function()
    {
         var $ele = $(this).attr('id');
            $(this).val('');
            $(this).css('color', '#000000');
    }).blur(function()
    {
           var $ele = $(this).attr('id');
            $(this).val($ele);
            $(this).css('color', '#a9a9a9')
    });
});

您可以直接在html中设置输入字段的值

<input id="Name" type="text" value="Name" name="Name">

或在页面加载时应用默认值:

$('input[type="text"]').each(function(){
   var $ele = $(this).attr('id');
                $(this).val($ele);
                $(this).css('color', '#a9a9a9')

});

HTML

<input id="Name" type="text" value="" name="Name">
<input id="Phone" type="text" value="" name="Phone" >
<input id="Email" type="text" value="" name="Email">
于 2012-09-30T17:59:44.733 回答
1

你需要修改你的js

$(function(){
    $('input').focus(function()
    {
        $(this)
            .val($(this).attr('name'))
            .css('color', '#000000')

    }).blur(function()
    {
            $(this).css('color', '#a9a9a9')
    });
})();​

如果您在“模糊”上设置值,您将失去当前值...我不确定这是否正是您想要的

于 2012-09-30T18:05:39.020 回答
0

将其应用于input而不是#name.

这将适用于所有输入。

或者给.class你想要改变的元素。

于 2012-09-30T17:59:34.373 回答
0

您可以使用 选择所有输入$('input[type="text"]'),但我认为您只想使用placeholderHTML 属性

于 2012-09-30T17:59:41.503 回答
0

查看jQuery 选择器。您现在正在做的是使用 ID 作为选择器。你有很多不同的选择......

如果您希望将“#Name”应用于页面上的所有输入,您可以将“#Name”替换为“input”,或者您甚至可以将通用类“class =”test”添加到要触发脚本的所有元素中然后将“#Name”替换为“.test”或“input.test”,仅用于具有该类名称的输入元素。

于 2012-09-30T18:01:01.383 回答