得到了这个代码(正在处理):
uniqueHead = {};
$("div.hleft h3").each(function () {
var thiz = $(this)
var thisValq = thiz.text();
var thisVal = thisValq.trim().toLowerCase().toString();
if(!(thisVal in uniqueHead) ) {
uniqueHead[thisVal] = "";
}
else {
$(this).parent().parent().css('border-color','red')
}
});
该代码适用于搜索结果列表,其中组的搜索结果可以拆分,即与“结果 2”同名的“结果 1”可以位于位置 1 和 12。
我需要做的是将所有具有相同文本的 h3 分组,然后正确排序并应用不同的类,以便我只在每组中显示结果 1(稍后可以创建一个显示类似结果的触发器)。
想象一下这样的代码:
<div class="blist">
<div class="hleft">
<h3>Three</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>One</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>Three</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>Two</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>One</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>Three</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>Two</h3>
</div>
</div>
<div class="blist">
<div class="hleft">
<h3>Three</h3>
</div>
</div>
上面不是“真正的”代码,但对于 JS 部分来说它无论如何都是有效的。 :) 我无法控制后端,因此无法更改结果的显示方式,因此无法更改用于排序等的 JS 解决方案。
最佳答案
为了处理分组部分,我认为您应该存储与您找到的每个名称的第一个实例相对应的 DOM 元素(目前,您只是记录一个空字符串)。然后,在当前将边框设置为红色的位置,从 DOM 中删除重复元素并将其插入到原始匹配元素之后。然后,您可以向每个重复元素添加一个类来隐藏它。
还没有测试过这个,但是类似的东西应该可以解决问题。
uniqueHead = {};
$("div.hleft h3").each(function () {
var thiz = $(this);
var thisValq = thiz.text();
var thisVal = thisValq.trim().toLowerCase().toString();
if(!(thisVal in uniqueHead) ) {
uniqueHead[thisVal] = thiz;
}
else {
// remove the element from the dom and place it after the original one
var originalElement = uniqueHead[thisVal];
originalElement.after($(this).remove().addClass("hiddenDuplicate"));
}
});
稍后如何显示重复项取决于您。您可以将每组重复项包装在一个父 div 中,然后当单击该 div 中的按钮时,显示所有子元素。
关于jQuery 分组匹配并对 1 和 2 应用不同的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053025/