1

I'm trying to mimic a placeholder behavior, so i try to save the original value on page load. using this code. I'm here cause it's not working. the value is empty.

$().ready(function() {
  $("input").prop("placeHolder", $(this).val());
  /*
  also tried:
       $("input").prop("placeHolder", $(this).attr("value"));
  */
}
4

3 回答 3

2

在您的原始代码$(this)不是当前input元素。它将是传递的任何对象this-$().ready()可能是document对象。(我测试过 - 它是!)

这应该满足您的要求:

$('input').prop('placeholder', function() {
    return this.value;
});

这个版本.prop将调用提供的函数,依次传递每个元素 as this,允许直接访问该 DOM 元素的其他属性。

于 2014-09-09T16:09:38.810 回答
2

尝试这个:

$(document).ready(function(){
    $("input").prop("placeholder", function(){
        return $(this).val()
    });
});

$().ready()猜你指的是$(document).ready()方法。

在您的情况下$(this),没有引用您的input. 它正在从这句话所在的地方获取父级。在这种情况下,$().

你可以做我上面写的,或者这也可以:

$(document).ready(function(){
    $("#input_id").prop("placeholder", $("#input_id").val());
});

这适用于一个输入,如果您想要另一种方法使其适用于所有输入,这也适用:

$(document).ready(function(){
    $("input").each(function(){
        $(this).prop("placeholder", $(this).val());
    });
});

请注意,在这种情况下$(this)确实引用了正在迭代的输入。

于 2014-09-09T16:14:36.177 回答
1

该属性区分大小写,因此它应该是“占位符。您可以使用一个函数来设置该属性:

$("input").prop("placeholder", function () {
    return $(this).val()
});

jsFiddle 示例

于 2014-09-09T16:10:04.770 回答