2013-01-24 45 views
0

一個div內部的示例文本:選擇一個DIV內的特定字符串和格式化

I am at the first line. 
I am at the second line. 
I am at the third line. 
I am at the end of the first paragraph. 

問題: 我想打一個腳本,將使:

  1. 所有「第一「會變成藍色
  2. 所有」秒「都會變成綠色
  3. 所有」第三「都會變成紅色並且大膽

Please see the non working code here..

增加了一個鏈接的代碼

+1

哪裏是你的代碼?這裏的人會幫助你,但不會爲你寫代碼。 –

+1

澄清:你在DIV中有一些純文本,你需要對第一個,第二個和第三個句子進行樣式設置(不管前三個句子後面有多少句)?句子可以在一段時間之外結束嗎?如用戶1743214所示,您是否可以控制文本?您是否可以預先在HTML元素中包裝該文本?另外,正如Steve-Wellens所建議的那樣,您是否可以提供任何標記或代碼?謝謝! – encoder

回答

2

在這裏你去

$(function(){ 
    $('#text').attr('value','first').css('color','#0000FF'); 
    $('#text').attr('value','second').css('color','#00FF00'); 
    $('#text').attr('value','third').css('color','#FF0000'); 
    $('#text').attr('value','third').css('font-weight','bold'); 
}); 
0

這將是幾乎不可能實現,如果工作了一篇文章或段落,它不會在我的點其他工作.. 查看唯一的解決方案將包括一個HTML標記,將定義這些標記,然後適用於他們的jQuery代碼,

<p class='paragraph'> 
<span class='firstline'>This is the first line.</span> 
<span class='secoundline'> This is the second line. </span> 
<span class='thirdline'> This is the third line.</span> 
<span class='endparagraph'>This is the end of the first paragraph.</span> 
</p> 

現在jQuery的一部分,你可以這樣做

$(function(){ 
    $('.firstline').css({'color':'blue' , 'font-weight':'bold'}); 
    ..... 

}) 
+0

這些文本是在div中。這裏:

This is the first line. This is the second line. This is the third line. This is the end of the first paragraph.

+0

對不起,但我怎麼知道...除了它無關緊要,如果他們是在一個div或什麼的,你只需要把正確的標記 –

0

您可以使用jQuery :nth-child選擇這樣做。您可以使用css()應用樣式或向段落添加類並使用CSS對其進行樣式設置(這將是理想的)。

我已經創建了兩個版本的JSFiddle:http://jsfiddle.net/RJ8sC/5/。你只需要將包裝器ID改爲你的,你應該很好。

這裏是爲快速參考jQuery代碼:

$(document).ready(function() { 
    $('#example p:nth-child(1)').css('color','blue'); 
    $('#example p:nth-child(2)').css('color','green'); 
    $('#example p:nth-child(3)').css({color:'red', 'font-weight': 'bold'}); 
}); 

// ALTERNATIVE USING CLASSES - THIS IS BETTER PRACTICE 

$(document).ready(function() { 
    $('#example2 p:nth-child(1)').addClass('first'); 
    $('#example2 p:nth-child(2)').addClass('second'); 
    $('#example2 p:nth-child(3)').addClass('third'); 
}); 
相關問題