如何使用jquery在输入字段中自动隐藏占位符文本

时间:2017-08-01 15:02:53

标签: javascript jquery html

我在这里有这个代码,它做了什么它隐藏了焦点上的占位符字段并使用jquery在模糊中显示它们但我需要有人一行一行地向我解释这个代码,因为我是初学者

$(function() {
  'use strict';

  // hide placeholder on form focus 

  $('[placeholder]').focus(function() {
    $(this).attr('data-text', $(this).attr('placeholder'));
    $(this).attr('placeholder', '');
  }).blur(function() {
    $(this).attr('placeholder', $(this).attr('data-text'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <h4 class="text-center"> Admin Login </h4>
  <input type="text" name="user" placeholder="Username" autocomplete="off">
  <input type="password" name="pass" placeholder="Password" autocomplete="new-password">
  <input type="submit" value="Login">
</form>

3 个答案:

答案 0 :(得分:1)

$(function() {}).... 
    is an anonymous function which gets called when js file gets loaded in the browser.

$('[placeholder]')
    Provides collections of elements objects having placeholder inside the form.

$('[placeholder]').focus(callback)
    This statement will bind the focus event to all the elements which supports placeholder.

callback()
    This is a function which gets called when above event gets fired.

Inside call back in above code two below statements are written
    $(this).attr('data-text', $(this).attr('placeholder'));
    // Above satement will pick text given in placeholder property and assign this to 'data-text' property

    $(this).attr('placeholder', '');
        //Above stement will make placeholder text empty by assigning emty string.

.blur(callback_b)
    This statement will bind the blur event to all the elements which supports placeholder.

callback_b()
    This is a function which gets called when blur event gets fired.

Inside callback_b() below code is written
    $(this).attr('placeholder', $(this).attr('data-text'));
    //This statement will take the value assigned to 'data-text' in focus event and assign it back to placeholder property.

希望这有帮助,请根据您的需要将其标记为答案。

答案 1 :(得分:0)

所以基本上它正在做的是当你关注元素时,它将占位符属性的值存储在data-text属性中,并将占位符设置为空。然后在模糊时,它只是将占位符设置为属性中的值。它存储在data-text属性中,以便以后检索。它没有特殊用途,除了像变量这样存储一个值。

如果你想知道什么     $(&#39; [占位符]&#39;)。focus(function(){ 是的,基本上它意味着如果你聚焦任何具有占位符属性的对象,请调用该函数。

答案 2 :(得分:0)

$( '[占位符]')

jQuery使用属性占位符

找到的任何对象

.focus(...)

在元素聚焦时执行内部代码

$(本).attr( '数据文本',$(本).attr( '占位符'));

此行暂时存储占位符(因此您可以稍后重新设置)

$(本).attr( '占位符', '');

这会从元素中清除占位符

.blur(...)

在元素模糊时执行内部代码

$(本).attr( '占位符',$(本).attr( '数据文本'));

此行将占位符设置为存储在临时位置的值(如上所述)