使用jQuery/Javascript添加占位符

7

如果页面上只有一个 <input>,我可以通过 jQuery 放置一个占位符:

<input type="text"/>

$(document).ready(function() {
    placeholders();
    function placeholders() {
        $('input[type=text]').each(function() {

            $(this).attr('placeholder', 'hello' );
        });
    }
});

然而,我在单个页面上有多个字段,如下所示:
<input type="text" class="first">
<input type="text" class="second">

我希望只在第一个 <input type="text"> 中添加占位符,该输入框具有 class="first"

如何仅为第一个匹配的文本添加占位符?

5个回答

3
$('input[type=text].first').attr('placeholder', 'hello' );

这里的input会选择所有的input标签[type=text]会选择类型为文本的输入框,然后.first会选择具有first类的子集。

如果你想选择第一个带有first类的输入框,则可以使用$('input[type=text].first').first()


1
$('input[type=text].first').attr('placeholder', 'hello' );

使用class选择器。

1
您可以尝试这个解决方案:
$('input[type=text].first').attr('placeholder', 'hello' );

1
我希望在第一个 class="first" 的文本框中添加占位符。如何只向第一个匹配的文本输入框添加占位符?请尝试使用选择器 "input[type=text][class=first]" 和 setAttribute() 方法来使用 document.querySelector()。

function placeholders() {
  document.querySelector("input[type=text][class=first]")
  .setAttribute("placeholder", "hello");
}

$(document).ready(placeholders);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="first">
<input type="text" class="second">


0
如果你想要一个元素特定的脚本,为了更好的性能,请使用ID而不是CLASS。
<input type="text" class="first" id="first">

$("#first").attr('placeholder', 'hello' );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接