1

我有这个 div,我想在第一句话中添加一些样式。

<div class="text">dfgdfg.asdhasd</div>

我正在尝试这段代码,但没有按预期工作。

var text = $('.text').html().split(".")[0]+".";

$(".text:contains("+text+")").css("color", "red");

演示

4

3 回答 3

2

See http://jsfiddle.net/wp5kw/

Assuming a paragraph of:

<p id="para"> This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!</p>

To grab all the sentences, use:

var sentences=$('#para').text() // get example text
        .match(/[^\.\!\?]+[\.\!\?]+/g) // extract all sentences
        .map(function(s){ // (optional) remove leading and trailing whitespace
            return s.replace(/^\s+|\s+$/g,'');
        });

To highlight the first sentence, use:

var count=0;
$('#para2').html(
    $('#para')
        .text()
        .match(/[^\.\!\?]+[\.\!\?]+/g)
        .map(function(s){
            s=s.replace(/^\s+|\s+$/g,'');
            return count++
                ? s
                : '<span style="color:red">'+s+'</span>'
        }).join(' ')
);

The regular expression assumes that periods, exclamation and question marks are used to terminate a sentence, and is:

[^\.\!\?]+         -- one or more non-sentence terminals
[\.\!\?]+          -- followed by one or more sentence terminals
于 2012-11-09T00:28:37.650 回答
2

这只有在页面上只有一个 .text 元素时才会起作用。

var elem = $('.text');
var textParts = elem.html().split(".");
var first = "<span class='red'>" + textParts.shift() + ".</span>";
elem.html(first + textParts.join("."));

如果有多个,则需要一个 each 循环。

var elems = $('.text');
elems.each( function(){
    var elem = $(this);
    var textParts = elem.html().split(".");
    var first = "<span class='red'>" + textParts.shift() + ".</span>";
    elem.html(first + textParts.join("."));
});

当然这使用一个类来设置颜色,基本类是

.text .red{
    color: #FF0000;
}

运行示例:http: //jsfiddle.net/a68dS/1/

于 2012-11-08T23:32:59.490 回答
0

您需要将其包装在一个元素中,您不能将 css 应用于文本节点:

var $div = $('.text');
var text = $div.text();

$div.html( text.replace(/.+?\./, '<span>$&</span>') );

演示:http: //jsbin.com/ezojic/1/edit

于 2012-11-08T23:35:44.580 回答