使用CSS或jQuery更改每行的颜色第一个单词

时间:2013-11-20 18:00:12

标签: jquery css

我试图定位每一行的第一个单词,将颜色更改为仅第一个单词。现在,后端正在填充textarea

<div class="items">
67 small businesses has worked with us since the beginning of time
<br>
<br>3:1 ratio of apple products to humans
<br>
<br>2400 hours clocked in 2012
<br>
<br>13.7 number of times “So what exactly do you do?” is asked weekly
<br>
<br>1628 number of Starbucks K Cups consumed
<br>
<br>32 collective years of creative experience<br></div>

我想要完成的是使用<span>或类似的东西在每个第一个单词前加jQuery

<div class="items">
    <span class="color">67</span> small businesses has worked with us since the beginning of time
    <br>
    <br><span class="color">3:1</span> ratio of apple products to humans
</div>

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:5)

拆分中断(或换行符?),并使用单词mathcing regex在第一个单词周围添加一个范围:

$('.items').html(function(_,html) {
    var lines = html.split(/<br\s*[\/]?>/gi);
    for (var i=lines.length; i--;) {
        lines[i] = $.trim(lines[i]).replace(/^(\w+)/, '<span class="red">$1</span>')
    }
    return lines.join('<br>');
});

FIDDLE

答案 1 :(得分:2)

在循环中尝试这样的事情:

 var firstWord = $(this).text().split(" ")[0];
 var newText = $(this).text().replace(firstWord, "<span class='color'>"+firstWord +"</span>");
 $(this).html(newText);