如何清除文本字段 onfocus 如果它包含零,如果它为空,则 onfocusout 然后放零

How to clear a textfield onfocus if it contain zero and onfocusout if its is empty then put zero?

本文关键字:如果 onfocusout 然后 何清除 包含零 文本 清除 字段 onfocus      更新时间:2023-09-26

如果文本字段包含零,如何清除文本字段onfocus,如果为空则清除onfocusout,则将其归零? 全局在每个文本字段中通过获取文本字段的类?

您可以使用

模糊和聚焦

$('textarea').on('focus', function () {
    if ($(this).val() == "0") {
        $(this).val("");
    }
});
$('textarea').on('blur', function () {
    if ($(this).val() == "") {
        $(this).val("0");
    }
});

演示

这里列出的一些回应听起来很棒,但我个人不会依赖JavaScript来解决这个问题,除非你绝对需要它在旧浏览器上运行。

文本区域和输入字段都具有 placeholder 属性。

<textarea placeholder="0"></textarea>

这让本机浏览器负责将值替换为 0。

我假设文本字段实际上是指文本字段而不是文本区域。

在文档级别(或字段上方的任何元素)全局捕获它们,并在 on 方法中使用选择器。

$(document).on('focusout', 'input[type=text]', function(){
    var $input = $(this);
    if ($input.val() == "")
    {
        $input.val("0");
    }
}).on('focus', 'input[type=text]', function(){
    var $input = $(this);
    if ($input.val() == "0")
    {
        $input.val("");
    }
});

JSFiddle here: http://jsfiddle.net/TrueBlueAussie/chHfP/