javascript 我想使用jQuery在html中使用data-*属性将占位符设置为文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19699699/
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
I want to set placeholder to textbox using data-* attribute in html using jQuery?
提问by Arul
I want to set placeholder using data-* attribute. I tried with jQuery. but not working. if i use id instead of all input type. its working.
我想使用 data-* 属性设置占位符。我用 jQuery 试过。但不工作。如果我使用 id 而不是所有输入类型。它的工作。
but i want common code to set placeholder for any input text fields in a page.
但我想要通用代码来为页面中的任何输入文本字段设置占位符。
html:
html:
<p>Login</p>
<input type="text" data-placeholder="Email" id="txtemail" />
<input type="password" data-placeholder="Password" id="txtpass" />
jQuery:
jQuery:
foctext = $('input:text').attr("data-placeholder");
$(this).val(foctext);
$(this).focus(function () {
if ($(this).val() == foctext) {
$(this).val("");
}
});
$(this).blur(function () {
if ($(this).val() == "") {
$(this).val(foctext);
}
});
please write correct solution for this. thank you
请为此编写正确的解决方案。谢谢
采纳答案by Maxim Ershov
I guess you can use jQuery .data() selector - read more here - http://api.jquery.com/data/
我想你可以使用 jQuery .data() 选择器 - 在这里阅读更多 - http://api.jquery.com/data/
$(document).ready(function(){
$('input[type=text]').each(function(){
var txt = $(this).data('placeholder');
$(this).attr('placeholder', txt);
});
});
回答by Maxim Ershov
Use this code :
$('input:text').each(function(){
var placeholder = $(this).data('data-placeholder');
$(this).attr('placeholder', placeholder);
});
回答by power_scriptor
Hi try this way,
你好试试这个方法
<p>Login</p>
<input type="text" data-placeholder="Email" id="txtemail" />
<input type="text" data-placeholder="Password" id="txtpass" data-type="password" />
$.each($('input:text, input:password'), function(key, value){
$(this).val($(this).attr("data-placeholder"));
$(this).focus(function(){
if($(this).attr("data-placeholder") == $(this).val()){
if($(this).attr('data-type') == "password"){
$(this).attr('type', 'password')
}
$(this).val('');
}
});
$(this).blur(function(){
if($(this).val() == "" ){
$(this).val($(this).attr("data-placeholder"));
}
if($(this).attr("data-placeholder") == $(this).val()){
$(this).attr('type', 'text')
}
});
});
See jsFiddle sample http://jsfiddle.net/sakNy/2/
参见 jsFiddle 示例http://jsfiddle.net/sakNy/2/