1

我想遍历线条元素。每个line元素都有item元素作为子元素。所以首先我遍历,然后我想解决某个项目元素,例如第三个。这是我的代码:

$(".pricetable .righttable .line:not(.blank)").each(function(j) {
    var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);
    currentLine.(".item").each(function(k) {
        $(".pricetable .righttable .line .item").eq(i).addClass("active");
    });
});

问题是我不知道如何使用item类来处理子元素。

currentLine.(".item").each(function(k)

这不起作用。

XML 过滤器应用于非 XML 值 ({0:#2=({}), length:1, prevObject:{length:3, prevObject:{0:#1=({}), context:#1# , 长度:1}, 上下文:#1#, 选择器:".pricetable .righttable .line:not(.blank)", 0:#2#, 1:({}), 2:({})},上下文:#1#,选择器:".pricetable .righttable .line:not(.blank).slice(0,1)"}) file:///C:/Users/xxx/lib/pricetable.js 第 112 行

编辑:
哇,我没想到我得到了如此好的和快速的响应!我想我会采用这个解决方案:

$(".pricetable .righttable .line:not(.blank)").each(function(j) {
    $(this).children(".item").eq(i).addClass("active");
});
4

5 回答 5

3
$(".pricetable .righttable .line:not(.blank)").each(function(j) {
    var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);
    currentLine.find(".item").each(function(k) {
        $(".pricetable .righttable .line .item").eq(i).addClass("active");
    });
});

http://api.jquery.com/find/

如果他们是 currentLine 的直接孩子,你应该能够children('.item')代替find('.item'). 这称为遍历 DOM。访问此页面 (http://api.jquery.com/category/traversing/) 并阅读其中一些功能的描述。如果您遍历很多,记住它们将非常有用:)

于 2011-09-08T12:11:10.433 回答
2
$('.pricetable .righttable .line:not(.blank)').find('.item').each(function() {
  // this point to child element - item
  // use $(this).addClass('active');
});
于 2011-09-08T12:11:28.147 回答
2

item如果你想对each的第 n 个做点什么line,这比看起来要容易得多:

var index = 3; // the third "item" element 
$(".pricetable .righttable .line:not(.blank) .item:nth-child(" + index + ")")
  .addClass("active");

看到它在行动

您还有其他想做的事情,但上述内容还不够吗?

于 2011-09-08T12:11:39.890 回答
2

在我回答您的问题之前略有改进:

var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j);

很容易替换为:

var currentLine = $(this);

其次,如果您希望在 中找到第三个.item元素$(this),请使用.find()

.find(".item:nth-child(3)");

无需遍历行。如果您必须遍历这些行,那么只需比较(As JavaScript 从 0k开始2计数) 就可以了。

于 2011-09-08T12:12:56.230 回答
1
$(".pricetable .righttable .line:not(.blank)").each(function() {
  $(this).find('.item:nth-child(2)').addClass('active');
});
于 2011-09-08T12:16:37.663 回答