我正在尝试获取placeholder
属性值,并使用fadeIn
值作为placeholder
值的标签执行for
,但它不起作用。
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:
input+label { display: none; }
脚本
$(document).ready(function() {
$('input[type="text"]').click(function() {
var sd = $(this).attr('placeholder');
$('label[for^=sd]').fadeIn();
});
});
答案 0 :(得分:11)
您正在选择文字字符串“sd”,而不是您的变量的值。试试这个:
var sd = $(this).attr('placeholder');
$('label[for^="' + sd + '"]').fadeIn();
答案 1 :(得分:5)
答案 2 :(得分:3)
你可能想要:
$('label[for^="' + sd + '"]').fadeIn();
您还没有正确使用<label for="...">
[doc] 。 for
的{{1}}属性应引用<label>
的{{1}}属性,而不是<input>
属性。您可能有兴趣将代码更改为:
id
和
placeholder
答案 3 :(得分:1)
如果你想让一个输入占位符在用户专注于它时消失,而不是在他们移除焦点时重新出现,这对我来说很有效。
$('#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'));
}
});
答案 4 :(得分:0)
我猜你的标签的选择器字符串是错误的$('label[for="'+sd+'"]').fadeIn();
答案 5 :(得分:0)
如果标签始终位于输入旁边(如CSS选择器所示),您可以尝试:
$(function(){
$(":text").bind("focus", function(){
$(this).next().fadeIn();
});
});
并完全跳过占位符属性。绑定到“焦点”可能比“点击”
更好