如何使用 jquery 获取占位符属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8416223/
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
How can I get placeholder attribute value using jquery?
提问by Suresh Pattu
I am trying to get the placeholder
attribute value and do a fadeIn
with the label which has the placeholder
value as a for
value, but it's not working.
我正在尝试获取placeholder
属性值并fadeIn
使用该placeholder
值作为for
值的标签,但它不起作用。
HTML:
HTML:
<html>
<body>
<form>
<input type="text" id="name" name="name" placeholder="First Name" />
<label for="First Name">First Name </label>
</form>
</body>
</html>
CSS:
CSS:
input+label { display: none; }
Script
脚本
$(document).ready(function() {
$('input[type="text"]').click(function() {
var sd = $(this).attr('placeholder');
$('label[for^=sd]').fadeIn();
});
});
采纳答案by PiTheNumber
回答by FishBasketGordo
You are selecting with the literal string "sd", not the value of your variable. Try this:
您选择的是文字字符串“sd”,而不是变量的值。尝试这个:
var sd = $(this).attr('placeholder');
$('label[for^="' + sd + '"]').fadeIn();
回答by Rob Hruska
You probably want:
你可能想要:
$('label[for^="' + sd + '"]').fadeIn();
You're also not using <label for="...">
correctly [doc]. The for
attribute of a <label>
should reference the <input>
's id
attribute and not its placeholder
attribute. You'd probably be interested in changing your code to:
您也没有<label for="...">
正确使用[doc]。a 的for
属性<label>
应该引用<input>
的id
属性而不是它的placeholder
属性。您可能有兴趣将代码更改为:
<label for="name">First Name</label>
and
和
var id = $(this).attr('id');
$('label[for^="' + id + '"]').fadeIn();
回答by William Howley
If you are trying to have an input placeholder dissapear when the user is focused on it, and than re-appear when they remove focus this worked well form me.
如果您试图让输入占位符在用户专注于它时消失,而不是在他们移除焦点时重新出现,那么这对我来说效果很好。
$('#inputRanges input').on('focus', function(){
if(!$(this).data('placeholder')){
$(this).data('placeholder', $(this).attr('placeholder'));
}
$(this).attr('placeholder', "");
}).on('focusout', function(){
if($(this).val()==""){
$(this).attr('placeholder', $(this).data('placeholder'));
}
});
回答by zuo
I guess your selector string for the label is wrong$('label[for="'+sd+'"]').fadeIn();
我猜你的标签选择器字符串是错误的$('label[for="'+sd+'"]').fadeIn();
回答by epignosisx
If the label will always be right next to the input (as the CSS selector shows) you could try:
如果标签总是紧邻输入(如 CSS 选择器所示),您可以尝试:
$(function(){
$(":text").bind("focus", function(){
$(this).next().fadeIn();
});
});
and skip the placeholder attribute altogether. Also binding to "focus" might be better than "click"
并完全跳过占位符属性。同样绑定到“焦点”可能比“点击”更好