jQuery 如果可见
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7103736/
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
jQuery if visible
提问by Adam
<div id="chatCenterMembers">
<div class="chatmember">
<a title="Blah Blah Blah">
<div class="newchatmessage" style="display: block;"></div>
How can I capture the visible div in an if statement?
如何在 if 语句中捕获可见的 div?
I have $(this)
set to <div class="chatmember">
- second line from the top.
我已经$(this)
设置为<div class="chatmember">
- 从顶部开始的第二行。
I've been working with below but had now luck so far.
我一直在下面工作,但到目前为止运气很好。
if($(this+' a div.newchatmessage').filter(":visible")) {
Above just drops out...
以上只是掉线...
I've also tried below and it doesn't work either
我也在下面尝试过,它也不起作用
if ($(this + 'a div.newchatmessage').is(':visible')) {
采纳答案by Andreas Niedermair
for any detailed information on this method, just scroll down a bit ... there's a bunch of examples!
有关此方法的任何详细信息,只需向下滚动一点...有很多示例!
edit (thanks for the hint @Wesley Murch):
if this does not work, your selector might be wrong ... $(this+' a div.newchatmessage')
looks quite strange ... it might rather be $('a div.newchatmessage', this)
or $('a div.newchatmessage', $(this))
depending on this
being a jQuery-variable or not
编辑(感谢@Wesley Murch 的提示):如果这不起作用,则您的选择器可能是错误的......$(this+' a div.newchatmessage')
看起来很奇怪......它可能是$('a div.newchatmessage', this)
或$('a div.newchatmessage', $(this))
取决于this
是否是 jQuery 变量
回答by Joakim Johansson
Use .is()
to check if an element fills a certain requirement, like such:
使用.is()
检查元素填充有一定要求的,像这样的:
if ($(this).find('a div.newchatmessage').is(':visible'))
Or, if you want it more readable:
或者,如果您希望它更具可读性:
var element = $(this).find('a div.newchatmessage');
if (element.is(':visible')) {
// Do your thing
}
回答by Ken Johnson
I ran into a similar situation and wanted to note that you should be wary of the jquery selector returning more than one element. I believe the .is(':visible') check will only evaluate the first element in the array. You can check to see if all elements returned by that selector are visible with something like this.
我遇到了类似的情况,并想指出您应该警惕 jquery 选择器返回多个元素。我相信 .is(':visible') 检查只会评估数组中的第一个元素。您可以检查该选择器返回的所有元素是否都可以通过类似的方式看到。
if($('.someElementWithThisClass:visible').length > 0){
//Do it to it
}