将值更改为占位符(输入字段)

Joh*_*ith 3 jquery replace

我想用jQuery将value属性更改为占位符.所以结果将是这样的

原版的

<input type="text" value="Enter name" />
Run Code Online (Sandbox Code Playgroud)

我想改变的是什么

<input type="text" placeholder="Enter name" />
Run Code Online (Sandbox Code Playgroud)

我只找到了改变""之间的实际文本的解决方案,而不是之前的文本.所以replaceWith,replaceAll似乎不起作用.

有人知道如何解决这个问题?

Ahs*_*hid 14

你可以用

.removeAttr('value') 删除属性

例:

$('input[type=text]').removeAttr('value');
Run Code Online (Sandbox Code Playgroud)

并添加新属性

.attr('placeholder','Enter name')

例:

$('input[type=text]').attr('placeholder','Enter name');
Run Code Online (Sandbox Code Playgroud)

如建议的那样 rcdmk

你可以用链接方法:

    $('input[type="text"]').each(function() { 
        var $this = $(this); 
        $this.attr("placeholder", $this.attr("value")).removeAttr("value"); 
    });
Run Code Online (Sandbox Code Playgroud)

  • 我会添加一个答案,但这很适合.只需要补充说你可以链接方法:`$('input [type ="text"]').each(function(){var $ this = $(this); $ this.attr("placeholder" ",$ this.attr("value")).removeAttr("value");});` (4认同)