2010-02-22 136 views
1

我有这样的HTML:jQuery的,追加HTML

<h1> Text1 Text2 </h1> 

我通过jQuery要改变这个HTML中:

<h1> <span>Text1</span> Text2 </h1> 

我我头上来了只是追加和正则表达式(也许你有另一个想法),不幸的是我没有“正则表达式”的经验。 “Text1”是多变的。它应该是“h1”中的第一个文字 有人能帮助我!

谢谢!

回答

3

假设你想要包装的跨度每个H2的第一个字,而H2是保证里面有没有HTML标记,你如下做到这一点:

// For each H2. 
$('h2').each(function() { 
    // Get text. 
    var text = $(this).text(); 
    // Split into words. 
    var words = text.split(' '); 
    // Wrap the first word. 
    if (words.length > 0) words[0] = '<span>' + words[0] + '</span>'; 
    // Join the results into a single string. 
    var result = words.join(' '); 
    // Put the results back into the H2. 
    $(this).html(result); 
}); 

或者使用正则表达式:

// For each H2. 
$('h2').each(function() { 
    $(this).html($(this).text().replace(/^(\W*)\b(\w+)\b/, '$1<span>$2</span>')); 
}); 
+0

+1美元,2美元。我不知道你可以这样做。 – Joel 2010-02-22 01:14:08

+0

这太棒了! – AlexC 2010-02-22 01:27:06

0

获取文本

var text = $('h2').text(); 
var $arr = text.split(' '); 

现在你必须在数组值,可以循环init或仅仅指刚使用$改编[0]和$改编[1]用它无论你有多喜欢它。

1

下面将包裹第一h1标签的第一个字用span标签。

$("h1").html($("h1").html().replace(/^\w+\b/, function(result) { 
    return "<span>" + result + "</span>"; 
})); 
+0

text1将要改变,应该是自动第一个字 – AlexC 2010-02-22 00:41:21

+0

更新以匹配任何字。 '\ w'匹配单词字符(字母,数字和下划线)。为了更通用,你可以使用'.'来匹配任何东西。 – Joel 2010-02-22 01:11:19