Jquery - 恢复更改的占位符?

时间:2015-03-06 10:33:34

标签: jquery placeholder restore

我知道如何更改占位符,但如果需要,我该如何更改?

我已经尝试过了,但它没有改变它......

$('[name^="u_"]').change(function(){
    if($(this).is(":checked")) {
        $(this).next("input, select").attr("disabled",true);
        $(this).next("input, select").attr("placeholder", "New Holder");

    } else {
        $(this).next("input, select").attr("disabled",false);
        $(this).next("input, select").attr('defaultValue') 
    }
});

我在多个输入上使用此代码。每个字段都使用以下内容设置默认占位符:

<input type='checkbox' name='u_id'><input type="text" name="id" placeholder="ABC123">

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以为我的代码中的旧占位符设置另一个属性,我将data-placeholder保留旧值,当您希望它可以用作旧占位符时。

<强> HTML

<input type='checkbox' name='u_id'>
<input type="text" name="id" placeholder="ABC123" data-placeholder="ABC123">
                                                  ^^^^^^^^^^^

<强>的jQuery

$('[name^="u_"]').change(function(){
    if($(this).is(":checked")) {
        $(this).next("input, select").attr("disabled",true);
        $(this).next("input, select").attr("placeholder", "New Holder");

    } else {
        old_place_holder = $(this).next("input, select").attr("data-placeholder");
        $(this).next("input, select").attr("disabled",false);
        $(this).next("input, select").attr('placeholder',old_place_holder) ;
    }
});

<强> Demo