jQuery 将值更改为占位符(输入字段)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11432144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change value to placeholder (input field)
提问by JohnSmith
I want to change the value attribute to placeholder with jQuery. So the result would be something like this
我想使用 jQuery 将 value 属性更改为占位符。所以结果会是这样的
Original
原来的
<input type="text" value="Enter name" />
What I want to change above to
我想改变上面的内容
<input type="text" placeholder="Enter name" />
I have only found solutions for changing the actuall text between the "" and not the text before those. So replaceWith, replaceAll does'nt seems to work.
我只找到了更改“”之间实际文本的解决方案,而不是之前的文本。所以replaceWith,replaceAll 似乎不起作用。
Someone having an idea how to solve this?
有人知道如何解决这个问题吗?
回答by Ahsan Khurshid
You may use
您可以使用
.removeAttr('value')
to remove attribute
.removeAttr('value')
删除属性
Example:
例子:
$('input[type=text]').removeAttr('value');
and add new attribute with
并添加新属性
.attr('placeholder','Enter name')
.attr('placeholder','Enter name')
Example:
例子:
$('input[type=text]').attr('placeholder','Enter name');
As suggested by rcdmk
正如所建议的 rcdmk
You may do it chaining the method:
您可以将方法链接起来:
$('input[type="text"]').each(function() {
var $this = $(this);
$this.attr("placeholder", $this.attr("value")).removeAttr("value");
});
回答by Code Spy
<input type="text" id="searchInput" value="enter text...">
var plcehldr = "enter text...";
$( "#searchInput" ).focusin(function() {
$(this).removeAttr("value");
});
$( "#searchInput" ).focusout(function() {
$(this).attr("value",plcehldr);
});