更改现有jQuery以使其成为span占位符

更改现有jQuery以使其成为span占位符,jquery,placeholder,Jquery,Placeholder,我有一些jQuery,只要我的与输入的名称和ID匹配,它就会提供一个占位符。但是,事实并非如此,因此我决定只使用作为占位符。有人能帮我修改jQuery,使我使用的类“holder”工作吗?目标是让占位符保持焦点,在输入存在时消失,然后在输入消失时重新出现 以下是我正在使用的HTML: <div id="placeholder"> <span class="holder">This is the placeholder...</span> <%=

我有一些jQuery,只要我的
输入的
名称和ID匹配,它就会提供一个占位符。但是,事实并非如此,因此我决定只使用
作为占位符。有人能帮我修改jQuery,使我使用的
类“holder”工作吗?目标是让占位符保持焦点,在输入存在时消失,然后在输入消失时重新出现

以下是我正在使用的HTML:

<div id="placeholder">
  <span class="holder">This is the placeholder...</span>
  <%= f.text_area :body, :id =>"Placeholder" %>
</div>
$(document).ready(function() {
    $('textarea').keyup(function() {
        if ($(this).val().length) {
            $('label[for="' + $(this).attr('name') + '"]').hide();
        } else {
            $('label[for="' + $(this).attr('name') + '"]').show();
        }
    });
});

谢谢

像这样的方法应该会奏效:

$(function() {
    $("span.holder + textarea").keyup(function() {
        if($(this).val().length) {
            $(this).prev('span.holder').hide();
        } else {
            $(this).prev('span.holder').show();
        }
    });        
});
如果页面上的所有文本区域前面都有
span.holder
,则这应该适用于它们。

您希望绑定到和事件,并将
绝对定位在
上。从一些CSS开始:

#placeholder {
    position: relative;
}

.holder {
    position: absolute;
    top: 2px;
    left: 2px;
    display: none;
}
然后是jQuery:

$('.holder').click(function() {
    $(this).siblings('textarea').focus();
});
$('#Placeholder').focus(function() {
    $(this).siblings('.holder').hide();
});
$('#Placeholder').blur(function() {
    var $this = $(this);
    if($this.val().length == 0)
        $(this).siblings('.holder').show();
});
$('#Placeholder').blur();
最后一个
$(“#占位符”).blur()调用用于初始化
的状态,以便在
以内容开头时处于正确的状态

还有一个快速演示:

顺便说一句,将
id=“placeholder”
id=“placeholder”
放在同一页中可能会导致一些混乱。你最好为你的
id
属性选择一个标准方案(
camelCase
单词和连字符
,或者其他什么),并坚持下去。只是大小写上的差异可能会让人困惑,可能看起来像是打字错误