通过数组过滤以匹配文本(jQuery / Javascript)

Posted

技术标签:

【中文标题】通过数组过滤以匹配文本(jQuery / Javascript)【英文标题】:Filtering through an array to match the text (jQuery / Javascript) 【发布时间】:2017-08-06 23:52:54 【问题描述】:

我有一个名为$myList 的无序列表。每次在输入中输入一个字符串 ($entry) 时,我都想遍历列表以查看该字符串是否已经在列表中。如果是,我想删除包含匹配字符串的列表项。无论哪种方式,新字符串都会被添加并成为新的列表项。

这是我最近尝试过的:

$myList.text().filter($entry).remove();


$myList.append($entry);

我不喜欢.text().filter(),但我尝试过的其他方法也没有奏效。

有什么简单的方法可以做到这一点?

【问题讨论】:

什么是$myListliul? for 循环即。 w3schools.com/js/js_loop_for.asp 这是一个 ul ........ 【参考方案1】:

filter 方法应该作用于列表项,而不是作用于 text() 值,因为它是您可能需要删除的列表项之一。 filter 方法需要一个 function 作为参数。该函数应该确定迭代项的text() 值是否是条目文本。然后remove 将起作用:

$('li', $myList).filter(function ()  
    return $(this).text() == entry;
).remove();

$('button').click(function () 
    var entry = $('input').val();
    var $myList = $('ul');
    $('li', $myList).filter(function ()  
        return $(this).text() == entry;
    ).remove();
    $('<li>').text(entry).appendTo($myList); // add item at end of list
    $('input').val(''); // clear input
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input><button>Add</button>
<ul></ul>

【讨论】:

【参考方案2】:
$myList.find("li").filter(function()  // for each list item
    return $(this).text() === $entry;  // pick those who have the text equal to $entry
).remove();                           // remove them

$("<li></li>").text($entry)            // create a new list item
              .appendTo($myList);      // add it to $myList

【讨论】:

【参考方案3】:

我使用了.each 函数;它遍历选择器内的所有项目。我没有使用.filter,因为我认为.each 会提供更直观的编程体验,因为你们都想检查是否存在某些东西,如果存在则将其删除,并将相同的项目附加到另一个列表中。

$myList = $("#myList");
$entry = $("#entry");
$newList = $("#newList");

$entry.on('input', function () 
  entryText = $entry.val();
  $myList.find("li").each(function () 
    if ($(this).html() == entryText) 
      $("<li>")
        .append($(this).html())
        .appendTo($newList);
      $(this).remove();
    
  );  
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Let's filter some tags<br />

<ul id="myList">
	<li>css</li>
	<li>js</li>
	<li>so</li>
	<li>sass</li>
	<li>haml</li>
</ul>

<input type="text" id="entry" />

<ul id="newList">
</ul>

【讨论】:

以上是关于通过数组过滤以匹配文本(jQuery / Javascript)的主要内容,如果未能解决你的问题,请参考以下文章

停止 jQuery 自动完成以过滤/搜索结果并填充整个源数组数据

jquery过滤器搜索应根据文本选择匹配的DIV

jQuery中的Grep与过滤器?

任何 jquery 1.3 兼容插件,使用用户文本输入过滤下拉列表,并根据匹配的输入字符串数进行分组

抓取网页数据

使用 Jquery Each 在 Javascript 对象和数组中查找匹配项