我試圖將多個值的數組傳遞給函數,該函數將檢查值是否存在於div列表中,如果是,則用紅色背景。比較我的數組作品,直到數組中有多個值
我的代碼工作時,我傳遞一個任意字符串作爲參數,它有效,當我有一個數組只有一個值。然而,一旦我的陣列有兩個或更多的值,它似乎打破了,並沒有在控制檯中的信息來暗示我。
我相信問題是與我如何編寫比較函數,但它可以還與我如何通過陣列說謊。
var postList = document.getElementsByClassName("post");
var userList = new Array();
//compares the user's keyword entries to the text in the divs, and marks "matching" divs with a red background
function listComparison(collection, searchText) {
for (var i = 0; i < collection.length; i++) {
if (collection[i].innerText.toLowerCase().indexOf(searchText) > -1) {
collection[i].style.backgroundColor = "red";
}
}
}
//adds user entries to an array on click and clears out the textarea
document.getElementById("save").addEventListener("click", function() {
var listEntry = document.getElementById("listEntries").value;
userList.push(listEntry);
document.getElementById("listEntries").value = "";
console.log(userList);
})
//event listener for the button that runs the collectionContains function above
document.getElementById("run").addEventListener("click", function() {
listComparison(postList, userList);
});
div {
background: #d0dbe6;
margin: 5px;
width: 50%;
}
#list {
width: 300px;
height: 100px;
}
<textarea placeholder="Enter words here one at a time and click 'Add to Filter'" id="listEntries"></textarea>
<br>
<button id="save" for="listEntries">Add to Filter</button>
<button id="run">Run Filter</button>
<div class="post">religion</div>
<div class="post">cats</div>
<div class="post">hotdogs</div>
<div class="post">babies</div>
<div class="post">test me please</div>
<div class="post">filler</div>
<div class="post">lorem ipsum</div>
<div class="post">your mom</div>
<div class="post">religion again</div>
<div class="post">build a wall</div>
<div class="post">no it's becky</div>
<div class="post">anything with religions in it is screwed!</div>
謝謝!非常棘手的是有一個'String.prototype.indexOf()'和'Array.prototype.indexOf()';那與我頭腦混爲一談。我也不習慣在for循環內直接嵌套循環。 – TylerH