jQuery:用来自文本输入的用户输入替换attr值占位符

时间:2015-09-11 16:20:29

标签: jquery input placeholder replacewith

使用.replaceWith().val()我可以替换标题,但在尝试访问输入的placeholder .attr()时,我无法替换它。这就是我所拥有的:

<p class="title">Title</p>
<p><input class="placeholder" type="text" placeholder="Placeholder" disabled /></p>
<p><input class="newText" type="text" /></p>
<p><input class="newPlaceholder" type="text" /></p>
<p><input type="button" class="button" title="button" /></p>

$("input.button").click(function(){
    var newText = $("input.newText").val();
    $("p.title").replaceWith(newText);

    var newPlaceholder = $("input.newPlaceholder").val();
    $("input.placeholder").attr("placeholder").replaceWith(newPlaceholder);
});

JSFiddle

1 个答案:

答案 0 :(得分:3)

.replaceWith()不用于设置HTML元素的属性。您想使用.prop()

  

获取匹配元素集中第一个元素的属性值,或为每个匹配元素设置一个或多个属性

要设置文本框的占位符属性,可以使用.prop(),如下所示:

var newPlaceholder = $("input.newPlaceholder").val();
$("input.placeholder").prop("placeholder", newPlaceholder);

updated your JSFiddle展示了一个例子。

相关问题