在焦点上只显示一个元素
on focus display just one element
我有一个简单的问题:
我有一个表格:
<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) 聚焦时我想要提交按钮 (.comment-button) 使用jQuery.
显示
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$('.comment-button').fadeIn(800);
});
});
这很好用。 问题 是我在 foreach 循环中有 表单,当我聚焦一个文本区域时,所有按钮都被选中。所以我 试图用 'this' 关键字 来做到这一点,就像这样:
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$(this).find('.comment-button').fadeIn(800);
});
});
但是那个没有用。在尝试了很长时间之后,我只是觉得自己的口语不够 jQuery 无法掌握这个简单的任务,于是向知情人士寻求帮助!
提前谢谢!
那是因为按钮是textarea的兄弟元素
$(this).siblings('.comment-button').fadeIn(800);
find
将尝试在文本区域中查找子元素,因此它永远找不到您的按钮:
你可以使用siblings
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$(this).siblings('.comment-button').fadeIn(800);
});
});
兄弟是这个问题的解决方案,但如果您将提交按钮包装在任何包装器(div 或跨度)中,则不再有效。
这会更安全 -
$(this).closest("form").find('.comment-button').fadeIn(800);
除了这 3 个答案之外,还有其他方法可以获得正确的元素,
$(this).parent().find('.comment-button').fadeIn(800);
或
$(this).next().next().fadeIn(800);
或
$(this).nextUntil('.comment-button').next().fadeIn(800);
我有一个简单的问题:
我有一个表格:
<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) 聚焦时我想要提交按钮 (.comment-button) 使用jQuery.
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$('.comment-button').fadeIn(800);
});
});
这很好用。 问题 是我在 foreach 循环中有 表单,当我聚焦一个文本区域时,所有按钮都被选中。所以我 试图用 'this' 关键字 来做到这一点,就像这样:
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$(this).find('.comment-button').fadeIn(800);
});
});
但是那个没有用。在尝试了很长时间之后,我只是觉得自己的口语不够 jQuery 无法掌握这个简单的任务,于是向知情人士寻求帮助!
提前谢谢!
那是因为按钮是textarea的兄弟元素
$(this).siblings('.comment-button').fadeIn(800);
find
将尝试在文本区域中查找子元素,因此它永远找不到您的按钮:
你可以使用siblings
$(document).ready(function() {
//display the comment button when the comment textarea is focused
$('.comment-input').focus(function() {
$(this).siblings('.comment-button').fadeIn(800);
});
});
兄弟是这个问题的解决方案,但如果您将提交按钮包装在任何包装器(div 或跨度)中,则不再有效。
这会更安全 -
$(this).closest("form").find('.comment-button').fadeIn(800);
除了这 3 个答案之外,还有其他方法可以获得正确的元素,
$(this).parent().find('.comment-button').fadeIn(800);
或
$(this).next().next().fadeIn(800);
或
$(this).nextUntil('.comment-button').next().fadeIn(800);