无法使用jquery删除占位符

时间:2015-02-02 10:36:26

标签: javascript jquery html css user-interface

我想在用户聚焦输入文本字段后删除占位符

   $('#keyfob').attr('placeholder','Please click here for Key Fob scanning to work');

        $('#keyfob').attr('placeholder', function () {
            this.toggle = !this.toggle;
            return this.toggle ? $(this).data('placeholder') : "";
        });
    }, 1500);

这是我用来显示闪烁占位符的函数,而密钥卡是字段ID,我已经在字段的模糊事件中返回此代码。

所以关注这个领域我必须隐藏或删除闪烁的占位符文本。

$('#keyfob').attr('placeholder','');

这是我用来删除或隐藏占位符的函数,但不知何故它没有隐藏。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用onfocusonblur个事件,并在各自的处理程序中清除或设置占位符的文本。试试这个,

解决方案1 ​​

HTML:

<input type="text" id="keyfob" class="customform col-sm-12 text-red" data-required='true' placeholder="Please click here to Key Fob scanning work">

jQuery:

$("#keyfob").on("focus", function(){
    previousElement = $(this);
    placeholderText = $(this).attr("placeholder");
    $(this).attr("placeholder", "");
});

$("#keyfob").on("blur", function(){
    $(previousElement).attr("placeholder", placeholderText);
});

注意: 如果您有多个input元素,则只需引用使用相同class属性的元素。这将使其他一切工作。

jsFiddle

解决方案2

如果您有一个输入元素,那么您可以更轻松地处理它。试试这种方式,

$('#keyfob').on("focus blur", function(){
    $(this).attr("placeholder") == "" ? $(this).attr("placeholder", "Please click here for Key Fob scanning to work") : $(this).attr("placeholder", "");
});

jsFiddle

解决方案3

更新代码: 要让placeholder闪烁,请将内容placeholder清空,然后在预定义的setInterval内重新填充。并onfocus使用clearInterval清除闪光灯setInterval

jQuery:

previousElement = $("#keyfob");
placeholderText = $("#keyfob").attr("placeholder");

$("#keyfob").on("focus", function(){
    $(this).attr("placeholder", "");
    clearInterval(blinker);
});

$("#keyfob").on("blur", function(){
    $(previousElement).attr("placeholder", placeholderText);
        console.log(previousElement);
    blinker = setInterval(function(){
        $("#keyfob").attr("placeholder") == "" ? $("#keyfob").attr("placeholder", "Please click here for Key Fob scanning to work"): $("#keyfob").attr("placeholder", "");
    }, 1000);
});

$("#keyfob").blur();

jsFiddle