簡體   English   中英

jQuery:如果span包含以下任何一個單詞,請添加此類

[英]jQuery: If span contains any of these words, add this class

我已經搜索了幾個小時,無法相信我在任何地方都找不到答案。

我們有一個聊天室。 這是用於此的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上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM