jQuery从列表1中删除不在列表2中的项目 [英] jquery Remove items from list 1 not in list 2

查看:66
本文介绍了jQuery从列表1中删除不在列表2中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看似非常简单的问题,但目前我的带宽非常有限,因此进行了搜索,但发现了

I have a seemingly very simple problem, but my bandwidth is so limited by now, and have searched SO but found a relevant question only applied to C#, I meant no luck yet.

HTML:

<ul class="first">
  <li data-id="1">One</li>
  <li data-id="2">Two</li>
  <li data-id="3">Thre</li>
  <li data-id="4">Four</li>
  <li data-id="5">Five</li>
  <li data-id="6">Six</li>
</ul>
<ul class="second">
  <li data-id="1">One</li>
  <li data-id="2">Two</li>
  <li data-id="3">Thre</li>
  <li data-id="4">Four</li>
</ul>

我想从第一个中删除最后两个项目(因此从五个和六个中删除),因为它们在第二个中不存在.顺序实际上并不重要.该示例简化了我的问题. 基本上没有明确的想法可以实现这一点,对不起,因此,每当尝试使用.length检查时,我都会删除所有前几项.

I want to remove the last 2 items from the first (hence Five and Six), because they do not exist in the second. Order is not important actually. The sample to simplify my problem. Basically no clear idea to achieve this, sorry, so whenever I tried with .length check, I remove all the first items.

任何提示都非常感谢.谢谢

Any hint is very much appreciated. Thanks

已更新: 对不起这是我的错. 顺序实际上并不重要":我的意思是列表可能是无序的,例如:

UPDATED: Sorry my bad. "Order is not important actually": I meant the lists may be unordered like:

<ul class="second">
  <li data-id="3">Thre</li>
  <li data-id="1">One</li>      
  <li data-id="4">Four</li>
  <li data-id="2">Two</li>
</ul>

也适用于第一个.

推荐答案

如果要通过data-id属性评估等效性:

If you're assessing equivalence by the data-id attribute:

$('.first li').filter(
    function(){
        return !$('.second li[data-id="' + $(this).data('id') + '"]').length;
    }).remove();​

JS Fiddle演示.

参考文献:

这篇关于jQuery从列表1中删除不在列表2中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆