0

したがって、入力(または他のタイプのel)でのデフォルトのテキストスワッピングには、このスニペットがあります

    <input class="js_text_swap" type="text" value="メールアドレスを入力してください" />

    if($('.js_text_swap').length > 0) {
        $('.js_text_swap').each(関数() {
            var that = $(this),
                値 = that.val(); // デフォルト値を記憶する

            that.focusin(関数() {
                if(that.val() === 値) {
                    その.val('');
                }
            });
            that.focusout(関数() {
                if(その.val() === '') {
                    その.val(値);
                }
            });
        });
    }


私の質問は次のとおりです
。1)これに対するより良い解決策はありますか?
2)ライブで追加された要素(ページがロードされた後にjsで追加された)でこれを機能させる方法を知っている人はいますか?

ありがとう

4

1 に答える 1

1

ジャップ!

HTML

<input placeholder="Click..." class="text" type="text">

CSS

.text{color:#aaa}
.text.focus{color:#444}

JS

$("input[placeholder]").each(function() {
    var placeholder = $(this).attr("placeholder");

    $(this).val(placeholder).focus(function() {
        if ($(this).val() == placeholder) {
            $(this).val("").addClass('focus');
        }
    }).blur(function() {
        if ($(this).val() === "") {
            $(this).val(placeholder).removeClass('focus');
        }
    });
});

http://yckart.com/jquery-simple-placeholder/

アップデート

ajax などで動作させるには、それを「プラグイン」に変換し、成功した ajax リクエストの後 (または動的にがらくたを作成した後) に呼び出す必要があります。

このようなもの(非常に単純な例):

jQuery.fn.placeholder = function() {
    return this.each(function() {
        var placeholder = $(this).attr("placeholder");

        $(this).val(placeholder).focus(function() {
            if ($(this).val() == placeholder) {
                $(this).val("").addClass('focus');
            }
        }).blur(function() {
            if ($(this).val() === "") {
                $(this).val(placeholder).removeClass('focus');
            }
        });
    });
};

$("input:text, textarea").placeholder();

$("button").on("click", function() {
    $(this).before('<input type="text" placeholder="default value" />');
    $("input:text, textarea").placeholder();
});

デモ

于 2012-09-25T00:57:12.423 に答える