简体   繁体   English

循环遍历jquery中的元素集

[英]looping through set of elements in jquery

$('form td .hint p') this jquery selector returns back a list [p,p,p,p,p,p] . $('form td .hint p')这个jquery选择器返回一个列表[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. 我想知道循环每一个的最佳方法是什么,检查他们的css值,并在css值=我想要的东西时做一些事情。

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. 在做mouseover和mouseout工作的时候,它有问题,因为我正在使用parent(),next()和child()来查找正确的元素,并且jquery瞬间插入一个div环绕我正在显示和隐藏的元素。 So basically I'm trying to force all other p elements that have display:block to hide every time mouseover occurs. 所以基本上我试图强制所有其他p元素有显示:阻止每次鼠标悬停时隐藏。

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.

Use each() : 使用each()

var displays = '';
$("p").each(function(i, val) {
  displays += "Paragraph " + i + ": " + $(this).css("display") + "\n";
});
alert(displays);

The reason this fails: 失败的原因:

var target = $("p");
var display = target[0].css("display");

is that target[0] is not a jQuery object. target[0] 不是 jQuery对象。 You could do this: 你可以这样做:

var display = $(target[0]).css("display");

Also, if you read the documentation for css() : 另外,如果您阅读css()的文档:

Return a style property on the first matched element. 返回第一个匹配元素的样式属性。

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. 其次,如果您正在检查CSS显示值,可能有一个值得使用的快捷方式。 For instance, you could do this: 例如,你可以这样做:

$("p").each(function() {
  if ($(this).css("display") == "none") {
    $(this).addClass("blah");
  }
});

but you can also use the :hidden and :visible selectors, so: 但你也可以使用:hidden:visible选择器,所以:

$("p:hidden").addClass("blah");

Checking values of css() calls is largely unreliable as you're only checking inline styles and not stylesheet values. 检查css()调用的值在很大程度上是不可靠的,因为您只检查内联样式而不是样式表值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM