[英]Select Random Words From Tag, Wrap In Italic
我有一堆動態生成的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>
所有標題將動態生成。
問題是$('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()文檔 (向下滾動1/2頁, function
參數不在早期版本中)
您可以使用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
, is
是斜體均is
和this
。 scrowler評論說,當所選單詞多次出現在標題中時,所有單詞都會被斜體顯示,但是我懷疑您打算對部分單詞進行斜體顯示。
修復相對簡單。 只需檢查單詞前后的空格即可。 您還必須允許使用^
和$
元字符在標題的開頭和結尾添加單詞。
理想情況下,我們可以使用\\b
,它是一個“單詞邊界”,但是當單詞以非字母字符結尾時,它似乎不起作用。
您還應該在將隨機選擇的單詞包含在正則表達式中之前對其進行轉義,以防它包含任何特殊字符。 我添加了轉義正則表達式,從Java中是否有RegExp.escape函數? 。
更新的代碼:
$('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會忽略該空格。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.