循环遍历jquery中的元素集
$('form td .hint p')
此 jquery 选择器返回一个列表 [p,p,p,p,p,p]
。
我想知道循环遍历每个元素、检查它们的 css 值并在 css 值 = 我想要的东西时执行某些操作的最佳方法是什么。
我有这个功能来显示和隐藏工具提示,但我只想一次显示一个工具提示。在进行 mouseover 和 mouseout 工作时,它是有问题的,因为目前我正在使用 Parent()、next() 和 child() 来查找正确的元素,并且 jquery 会立即插入一个 div 包围我正在显示和隐藏的元素。所以基本上我试图强制所有其他具有 display:block 的 p 元素在每次鼠标悬停时隐藏。
目前正在这样做:
target = $('form td .hint p');
target[0].css('display') gives an error.
target.css('display') seems to only return the css of the first one.
$('form td .hint p')
this jquery selector returns back a list [p,p,p,p,p,p]
.
I would like to know what's the best way to loop through each of those, check their css values, and do something if the css value = something I want.
I have this function to show and hide a tooltip, but I only want one tooltip to be shown at a time. While doing mouseover and mouseout works, it's buggy because currently I'm using parent(), next(), and child(), to find the right element, and jquery instantaneously inserts a div wrapping around the element I'm showing and hiding. So basically I'm trying to force all other p elements that have display:block to hide every time mouseover occurs.
Currently doing this:
target = $('form td .hint p');
target[0].css('display') gives an error.
target.css('display') seems to only return the css of the first one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
each()
:失败的原因
是 :
target[0]
不是 jQuery 对象。您可以这样做:此外,如果您阅读
css()
的文档:还有两点值得一提。
首先,我不建议您自己制作工具提示。为此获取众多插件之一。我之前使用过这个并且它完成了这项工作。
其次,如果您要检查 CSS 显示值,可能有一个值得使用的快捷方式。例如,您可以这样做:
但您也可以使用
:hidden
和:visible
选择器,因此:检查
css()
调用很大程度上不可靠,因为您只检查内联样式而不检查样式表值。Use
each()
:The reason this fails:
is that
target[0]
is not a jQuery object. You could do this:Also, if you read the documentation for
css()
:Two other points worth mentioning.
Firstly, I wouldn't advise doing a tooltip yourself. Get one of the many plugins for this. I've used this one previously and it did the job.
Secondly, if you're checking CSS display values, there may be a shortcut worth using. For instance, you could do this:
but you can also use the
:hidden
and:visible
selectors, so:Checking values of
css()
calls is largely unreliable as you're only checking inline styles and not stylesheet values.