jQuery:类和 .each()
我正在尝试将类添加到 div (.views-row) 内的元素。我遇到的问题是 .views-row 在页面上重复,这是不可避免的,并且我尝试设置样式的元素最终都具有相同的类,无论它们是否应该。代码可能更好地解释了它:
$(".views-row").each(function(){
if ($((this)" .field-name-field-warning:contains('High')").length) {
$((this)" .field-name-field-warning").addClass("fault-high");
$((this)" .field-name-field-warning .field-label").addClass("disappear");
$((this)" .field-name-field-warning .field-items").addClass("disappear");
}
if ($((this) ".field-name-field-warning:contains('Moderate')").length) {
$((this) ".field-name-field-warning").addClass("fault-moderate");
$((this) ".field-name-field-warning .field-label").addClass("disappear");
$((this) ".field-name-field-warning .field-items").addClass("disappear");
}
});
我想我在(这个)部分遇到了麻烦。有什么想法吗?
谢谢。
I'm trying to add classes to elements within a div (.views-row). The problem I'm having is that the .views-row repeats on the page, which is unavoidable, and the elements I'm attempting to style all end up the same classes regardless of whether they should or not. The code probably explains it better:
$(".views-row").each(function(){
if ($((this)" .field-name-field-warning:contains('High')").length) {
$((this)" .field-name-field-warning").addClass("fault-high");
$((this)" .field-name-field-warning .field-label").addClass("disappear");
$((this)" .field-name-field-warning .field-items").addClass("disappear");
}
if ($((this) ".field-name-field-warning:contains('Moderate')").length) {
$((this) ".field-name-field-warning").addClass("fault-moderate");
$((this) ".field-name-field-warning .field-label").addClass("disappear");
$((this) ".field-name-field-warning .field-items").addClass("disappear");
}
});
I guess I'm having trouble with the (this) part. Any thoughts?
Thank-you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想选择当前元素中的任何元素,有两种方法。
使用 $().find():
通过提供上下文(实际上与 find 相同) :
If you want to select any element within your current one there are two ways.
Using $().find():
By providing a context (which does practically the same as find):
使用 .find() :
use .find() on the this :
当 .addClass() 将为您迭代所有元素时,无需在此处使用 .each() 。
您可以从像这样的方法开始:
然后通过像这样的链接方法变得更奇特:
There's no need to use .each() here when .addClass() will iterate over all elements for you anyway.
You can start by moving to something like this:
Then get even fancier by chaining methods like this:
看起来您正在尝试使用
this
在元素中查找元素。您应该find
方法和filter
来过滤匹配元素集中的元素。这是完整的简化代码。
参考:.find()、.filter()
Looks like you are trying to find element within an element using
this
. You shouldfind
method for that andfilter
to filter the element in the matched set of elements.Here is the complete simplified code.
Reference: .find(), .filter()