我试图将存储在数组中的值与.text()值进行比较,然后在匹配时添加类。目前这是输出数组,文本值但布尔值返回false。
这是JSFiddle
代码
var comMem = [];
i = 0;
$(this).find(".com-member ul li").each(function() {
comMem[i++] = $(this).text();
});
$(".board-name").each(function() {
var boardName = $(this).text();
console.log( boardName );
console.log( comMem );
if(boardName == comMem) {
$(this).addClass(active);
}
});
谢谢!
答案 0 :(得分:4)
您需要使用indexOf()
indexOf()
方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1。
//Use .map()
var comMem = $(".com-member li").map(function() {
return $(this).text();
}).get(); //Get return you an array
//Since you want to iterate hence use li using descendant selector
$(".board-name li").each(function() {
var boardName = $(this).text();
//Use indexOf() to check it exists in an array
if(comMem.indexOf(boardName) > -1) {
$(this).addClass("is-active");
}
});
答案 1 :(得分:1)
您正在将boardName
与数组进行比较,以便您可以尝试:
$(document).ready(function() {
var comMem = [];
i = 0;
$(".com-member li").each(function() {
comMem[i++] = $(this).text();
});
$(".board-name").each(function() {
var boardName = $(this).text();
console.log( boardName );
console.log( comMem );
if(comMem.indexOf(boardName) > -1) {
$(this).addClass("is-active");
}
});
});
答案 2 :(得分:1)
您正在将字符串与
处的数组进行比较if(boardName == comMem) {
您需要使用indexOf()
if(comMem.indexOf(boardName) > -1)