jQuery:如果span包含这些单词中的任何一个,请添加此类



我已经搜索了几个小时,真不敢相信我在任何地方都找不到答案。

我们有一个聊天室。以下是它的HTML结构:

<p class="foo"><span>Irene says:</span> some words</p>
<p class="foo"><span>Joe says:</span> some other words</p>
<p class="foo"><span>Billie Jean says:</span> something else</p>
<p class="foo"><span>Gumby says:</span> Well, this is a boring conversation.</p>
<p class="foo"><span>Newbie says:</span> where am i?</p>

我想做的是将同一个类添加到所有包含人员名称的<span>标签中,并且只有当它们在.foo类中时,这样我才能使这些名称在聊天室中脱颖而出。我可以让它为一个名字工作:

$('.foo span:contains('+ Billie Jean +')').addClass('colorize');

我可以对数组使用相同的函数吗?

var staffers=new Array(
"Billie Jean",
"Joe",
"Gumby"
);

如果我在下面的[]中放入0、1或2,它对一个名称有效:

$('.foo span:contains('+ staffers[0] +')').addClass('colorize');

我想我可以把它改成[i],但当然,这不起作用。

我可以用纯HTML和CSS制作完全响应的布局,但我只知道几个基本的javascript函数,而且我必须查找我正在尝试做的每一件小事。我不希望超过5或6个名称需要它,所以为每个名称使用单独的:contains行可以是一种选择,但我想知道是否有更有效的方法来做到这一点。

提前感谢!

编辑:

有人在这里发布了一个不太有效的解决方案,但一旦我删除了if部分,它就起了作用。

for ( i = 0; i < staffers.length; i++ ) {
$('.foo span:contains('+ staffers[i] +')').addClass('colorize');
}

i也有一些增量,但我不记得说了什么。

不管你是谁,谢谢!

我认为这种方法比在循环中重新查询dom更快

var staffers=[
"Billie Jean",
"Joe",
"Gumby"
];
var elems = $('.foo span');
elems.each(function (){
var el = $(this);
staffers.forEach(function (item){
if (el.text().indexOf(item) > -1) {
el.addClass('colorize');
}
});
});

在纯ECMA5 javascript中,没有库。

CSS

.colorize {
background-color:yellow;
}

HTML

<p class="foo"><span>Irene says:</span> some words</p>
<p class="foo"><span>Joe says:</span> some other words</p>
<p class="foo"><span>Billie Jean says:</span> something else</p>
<p class="foo"><span>Gumby says:</span> Well, this is a boring conversation.</p>
<p class="foo"><span>Newbie says:</span> where am i?</p>

Javascript

var staffers = [
"Billie Jean",
"Joe",
"Gumby"];
// Find all spans contained within elements that have a class of `foo`, step through them all.
Array.prototype.forEach.call(document.querySelectorAll('.foo span'), function (span) {
// Store the text of the span for testing the content
var spanText = span.textContent;
// For the current span, step though some of the staffers names until matched.
staffers.some(function (staff) {
// Is the name contained in the text?
if (spanText.indexOf(staff) !== -1) {
// Yes. Add the `colorize` class to the current span.
span.classList.add('colorize');
// We found a match, no need to continue searching staffers.
return true;
}
// Current staff name was not matched. Continue searching staffers
return false;
});
});

关于jsFiddle

相关内容

最新更新