在焦点上只显示一个元素

时间:2015-10-01 06:21:04

标签: javascript jquery focus this

我有一个简单的问题:

我有一个表单

<form>
    <textarea type="text" name="comment_text" class="comment-input"></textarea>
    <div class="remaining"></div>
    <input type="submit" class="button comment-button" />
</form>

现在,当 textarea (.comment-text)聚焦时,我希望使用jQuery显示提交按钮(.comment-button)

$(document).ready(function() {
    //display the comment button when the comment textarea is focused
    $('.comment-input').focus(function() {
        $('.comment-button').fadeIn(800);
    });
});

这很好用。 问题是我在foreach循环中有表单,当我关注一个textarea时,所有按钮都被选中。所以我试图用这个&#39;这个&#39;关键字是这样的:

$(document).ready(function() {
       //display the comment button when the comment textarea is focused
        $('.comment-input').focus(function() {
            $(this).find('.comment-button').fadeIn(800);
        });
    });

无效。在经历了太长时间的尝试之后,我只是决定我不会说足够的jQuery来掌握这个简单的任务,并转向知道的人寻求帮助!
提前谢谢

4 个答案:

答案 0 :(得分:4)

这是因为按钮是textarea的兄弟元素

$(this).siblings('.comment-button').fadeIn(800);

答案 1 :(得分:1)

find将尝试在textarea中找到子元素,因此它永远不会找到您的按钮:

您可以使用siblings

$(document).ready(function() {
       //display the comment button when the comment textarea is focused
        $('.comment-input').focus(function() {
            $(this).siblings('.comment-button').fadeIn(800);
        });
    });

答案 2 :(得分:1)

兄弟姐妹是这个问题的解决方案,但是如果你在任何包装器(div或span)中包装提交按钮,那么它将不再有效。

这样可以更安全 -

label

答案 3 :(得分:1)

除了这3个答案之外,还有其他方法可以获得正确的元素,

$(this).parent().find('.comment-button').fadeIn(800);

$(this).next().next().fadeIn(800);

$(this).nextUntil('.comment-button').next().fadeIn(800);
相关问题