gpt4 book ai didi

jquery - 如何评估匹配的元素并将其分组在一起

转载 作者:行者123 更新时间:2023-12-01 01:18:41 24 4
gpt4 key购买 nike

如果我的 HTML 看起来像这样:

<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>yellow</h1></div>
<div><h1>yellow</h1></div>
<div><h1>yellow</h1></div>
<div><h1>green</h1></div>
<div><h1>pink</h1></div>

jQuery 中评估 h1 匹配数量的最佳方法是什么,如果特定 h1 的匹配计数 > 1,则将其 div 放入容器 div 中:

<div class="matches">
<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>red</h1></div>
</div>
<div class="matches">
<div><h1>yellow</h1></div>
<div><h1>yellow</h1></div>
<div><h1>yellow</h1></div>
</div>
<div><h1>green</h1></div>
<div><h1>pink</h1></div>

我对一个将每个 h1 返回给我的each()函数很着迷,但我不确定这是否是最好的方法(jQuery newb试图进入新领域)。

最佳答案

var $containers = $('div'),
$headings = $containers.find('> h1'),
targetContainer = 'body',
matches = {};

/*
* First we traverse through the headings
* pushing exact matches to a 'matches' object
*/
$headings.each(function() {
var $this = $(this),
text = $this.text();

if (typeof matches[text] === 'undefined') {
matches[text] = [];
}

matches[text].push($this.closest('div')[0]);
});

/*
* Remove the initial, unsorted collection
*/
$containers.remove();

/*
* Now let's see if we have duplicate
* headings.
*/
for (group in matches) {
if (matches[group].length > 1) {

/*
* Put them all in a '.matches' div
* and append to our target container
* e.g. body
*/
$('<div class="matches"></div>').html(matches[group]).appendTo(targetContainer);

/*
* Delete the group
* after use
*/
delete matches[group];
}
}

/*
* This is optional:
* I used two separate loops to
* put unmatched headings after the
* matched groups.
*
* You could use the if..else from
* the previous loop.
*/

for (group in matches) {
$(matches[group]).appendTo(targetContainer);
}

此代码甚至可以使用混合的、无序的集合,例如

<div><h1>red</h1></div>
<div><h1>green</h1></div>
<div><h1>yellow</h1></div>
<div><h1>red</h1></div>
<div><h1>red</h1></div>
<div><h1>yellow</h1></div>
<div><h1>red</h1></div>
<div><h1>yellow</h1></div>
<div><h1>pink</h1></div>
<小时/>

更新:

正如我提到的,可以将匹配和不匹配的组保留在一起 - 删除第二个 for..in 循环并使用 if..else 如下:

/* ...
* Now let's see if we have duplicate
* headings.
*/
for (group in matches) {
if (matches[group].length > 1) {

/*
* Put them all in a '.matches' div
* and append to our target container
* e.g. body
*/
$('<div class="matches"></div>').html(matches[group]).appendTo(targetContainer);
} else {
$(matches[group]).appendTo(targetContainer);
}
}

但是,由于 JavaScript 对象在内存中的存储方式,无法预测枚举的顺序。

关于jquery - 如何评估匹配的元素并将其分组在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7749017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com