从标签中选择随机字,用斜体包裹

时间:2014-06-13 02:03:37

标签: javascript jquery html

我有一堆动态生成的H1标签。 我想在标签中随机选择1个单词,并用斜体标签包装。

这就是我到目前为止所遇到的问题,它是第一个h1动态生成的内容,并将其复制到页面上的每个h1。 除此之外,它有效。

有什么想法吗?

var words = $('h1').text().split(' ');

// with help from http://stackoverflow.com/questions/5915096/get-random-item-from-array-with-jquery

var randomWord = words[Math.floor(Math.random()*words.length)];

// with more help from http://stackoverflow.com/questions/2214794/wrap-some-specified-words-with-span-in-jquery

$('h1').html($('h1').html().replace(new RegExp( randomWord, 'g' ),'<i>'+randomWord+'</i>'));

我的最终目标

<h1>This is a <i>title</i></h1>
<h1><i>This</i> is another one</h1>
<h1>This <i>is</i> the last one</h1>

所有标题都将动态生成。

http://codepen.io/anon/pen/uskfl

2 个答案:

答案 0 :(得分:4)

问题是$('h1')会在页面中创建所有h1标记的集合。

您可以使用html()方法的函数回调,它将遍历每个h1并将它们视为单独的实例

$('h1').html(function(index, existingHtml) {
    var words = existingHtml.split(' ');
    var randomWord = words[Math.floor(Math.random() * words.length)];
    return existingHtml.replace(new RegExp(randomWord, 'g'), '<i>' + randomWord + '</i>');

});

请参阅html() docs (向下滚动1/2页,function参数不在早期版本中)

答案 1 :(得分:2)

您可以使用jQuery的.each()来遍历h1

$('h1').each(function(){
    var words = $(this).text().split(' ');
    var randomWord = words[Math.floor(Math.random()*words.length)];
    $(this).html(
        $(this).html().replace(new RegExp( randomWord, 'g'),'<i>'+randomWord+'</i>')
    );
});

演示:http://jsfiddle.net/RT25S/1/

编辑:我刚刚注意到我的答案中的一个错误也在你的问题中,可能在其他答案中。

this is another one这样的标题中,isis都标注了this。 scrowler评论说,当所选单词多次出现在标题中时,所有单词都将用斜体显示,但我怀疑你是否打算将部分单词用斜体字。

修复相对简单。只需检查单词前后的空格。您还必须使用^$元字符在标题的开头和结尾添加单词。

理想情况下,我们可以使用\b,这是一个“单词边界”,但是当单词以非孤立字符结尾时,它似乎不起作用。

如果包含任何特殊字符,您还应该在将其包含在正则表达式中之前将其随机选中。我从Is there a RegExp.escape function in Javascript?添加了逃避正则表达式。

更新的代码:

$('h1').each(function(){
    var words = $(this).text().split(' ');
    var randomWord = words[Math.floor(Math.random()*words.length)];
    // Escape the word before including it in a regex in case it has any special chars
    var randomWordEscaped = randomWord.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

    $(this).html(
        $(this).html().replace(
            //new RegExp( '\\b' + randomWordEscaped + '\\b', 'g' ),
            new RegExp( '(^| )' + randomWordEscaped + '( |$)', 'g' ),
            '<i> ' + randomWord + ' </i>'
        )
    );
});

更新的JSFiddle:http://jsfiddle.net/RT25S/3/

请注意,我在<i>标记之前和之后添加了空格,因为正则表达式现在可以捕获它们。 (这仍然适用于标题开头/结尾的单词,因为HTML会忽略该空格。)

相关问题