【问题标题】:jquery .each() combing all values on each run throughjquery .each() 组合每次运行时的所有值
【发布时间】:2014-11-21 10:02:56
【问题描述】:

我的目标是根据元素所在位置的数据集对页面上的元素进行分组。内容已经被渲染到页面上,我想要一个 Location 标头,用于在其中举行的事件上方的每个唯一位置。页面的结构是类名 > 位置 > 上课时间

我正在做几个 .each() 循环来尝试找到我需要的东西,但是我认为应该是第一个每个循环的单独运行的值都被组合在一起。问题是,每个循环仍在运行多次。

$('.class-Info').each(function () 
{
    var className = $("h2").text();
    var eventLocations = [];
    $('.scheduledClass').each(function (index) 
    {
        eventLocations[index] = $(this).data("location");
    }); 

    var key = "";
    var uniqueLocations = [];
    $(eventLocations).each(function (index, location)
    {
        if (key !== eventLocations[index])
        {
            key = eventLocations[index];
            uniqueLocations.push(eventLocations[index]);
        }
     });

     console.log ("For " + className + " the locations are " + uniqueLocations);

});

这是我的代码。我希望我的问题是有道理的。看看控制台看看我得到的结果。

http://jsfiddle.net/qnpr9fbh/5/

【问题讨论】:

  • 刚刚做了一个小编辑,我意识到在 .scheduledClass 元素的每个循环期间它没有得到正确的 className。必须添加相同的$(this).find('h2')

标签: jquery grouping each


【解决方案1】:

我想我明白你想在这里得到什么。

http://jsfiddle.net/qnpr9fbh/7/

如果您像这样更新您的第一个 each 循环(添加 $(this).find),它将查找当前 .class-Info 中存在的 .scheduledClass 元素。以前,它只是在寻找所有。这会导致不同的、看似合适的控制台输出。

$(this).find('.scheduledClass').each(function (index) {
    eventLocations[index] = $(this).data("location");
});

// Edit: Also make sure you select the correct "h2" by adding the $(this).find()
var className = $(this).find("h2").text();

控制台输出:

对于 DocuSign 管理员帐户物流培训创建 DocuSign 数字工作流程:位置为位置待定的模板

用于创建 Docusign 数字工作流程:模板的位置是 测试1,威利斯大厦,位置待定

这是否符合您的要求?


jQuery 有一些方便的功能可以让你的代码变得更小更简洁:

$('.class-Info').each(function () {
    var className = $(this).find("h2").text(),
        eventLocations = $.map($(this).find('.scheduledClass'), function (elem) {
            return $(elem).data("location");
        }),
        uniqueLocations = $.unique(eventLocations.slice());

     console.log ("For " + className + " the locations are " + uniqueLocations);
});
  • .map() - 将循环选定的元素并从函数返回的项目中构建一个数组。
  • .unique() - 将减少 jQuery 元素的数组或列表,并将其减少为仅包含唯一值的数组。
  • Javascript Array.slice() - 我在 eventLocations 数组上调用它,因为.slice() 将克隆数组。必要的,因为.unique() 将修改它接收到的数组。所以只是给它一个副本,而不是修改原件。

【讨论】:

  • 感谢您提供的额外功能!我以前从未见过 map 或 unique,虽然已经忘记了,但我认出了 slice。
  • 澄清我的代码版本的解决方案。仅仅因为 each() 的迭代正在查看一个元素并不意味着下一个 jquery 选择器只会查看该块的内部?定义 $(this) 是将 jquery 限制在第一个元素内的代码的部分吗?
  • 是的,没错。当您执行 $('.class') 之类的选择器时,它会在所有 HTML 内部查找 .class 元素,但您可以通过先选择父元素然后像我一样调用 .find() 来将搜索限制为某事物的子元素。
  • 理解 this 在 Javascript 中的含义是了解代码在做什么的重要部分——尤其是 jQuery 代码。在 jQuery .each() 循环内部,this 是被迭代的元素。该元素也被传递到每个函数中。在 each 函数内部,元素是第二个参数。在 map 函数内部,它是第一个。我本可以在该 map 函数中使用 this 而不是 elem 并且代码的行为相同。
  • 示例:jsfiddle.net/14hpvhdn - 这篇文章很好地进一步解释了它 (remysharp.com/2007/04/12/jquerys-this-demystified)。如果你在谷歌上搜索“了解 jQuery”之类的内容,你应该会发现大量文章通过很好的示例进一步解释它
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 2016-07-13
  • 2010-11-21
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 2011-11-27
相关资源
最近更新 更多