【问题标题】:Filtering through an array to match the text (jQuery / Javascript)通过数组过滤以匹配文本(jQuery / Javascript)
【发布时间】:2017-08-06 23:52:54
【问题描述】:
我有一个名为$myList 的无序列表。每次在输入中输入一个字符串 ($entry) 时,我都想遍历列表以查看该字符串是否已经在列表中。如果是,我想删除包含匹配字符串的列表项。无论哪种方式,新字符串都会被添加并成为新的列表项。
这是我最近尝试过的:
$myList.text().filter($entry).remove();
$myList.append($entry);
我不喜欢.text().filter(),但我尝试过的其他方法也没有奏效。
有什么简单的方法可以做到这一点?
【问题讨论】:
标签:
javascript
jquery
arrays
loops
foreach
【解决方案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>