2012-10-30 80 views
1

如何將Weekend's顏色更改爲藍色如何在td中更改單詞的顏色(jquery)

我使用razor,我有一個標誌,枚舉它可以直接轉換爲字符串是這樣的:

var a = 1|2|6|7; 
var weekdayStr=a.ToString();//weekdayStr=="Monday, Tuesday, Weekend" 

和HTML:

<table> 
<tr> 
<td>Monday, Tuesday, Weekend</td></tr></table> 

如何只改變一個單詞的顏色,不是所有td文字?

+3

[你嘗試過什麼?](http://whathaveyoutried.com)提示:你」你需要將你想要的文本打包成某種HTML元素。 –

+0

它可以在一個跨度,如'​​週一的週末' – yitwail

回答

1
$.fn.replaceText = function(search, replace, text_only) { 
return this.each(function(){ 
    var node = this.firstChild, 
    val, 
    new_val, 
    remove = []; 
    if (node) { 
    do { 
     if (node.nodeType === 3) { 
     val = node.nodeValue; 
     new_val = val.replace(search, replace); 
     if (new_val !== val) { 
      if (!text_only && /</.test(new_val)) { 
      $(node).before(new_val); 
      remove.push(node); 
      } else { 
      node.nodeValue = new_val; 
      } 
     } 
     } 
    } while (node = node.nextSibling); 
    } 
    remove.length && $(remove).remove(); 
}); 
}; 

$("td").replaceText(/Weekend/g, "<span>Weekend</span>"); 
$('td span').css('color', 'blue'); 

reference from

+0

完美,謝謝 –

1
$(document).ready(function(){ 
    var build = ''; 
    var data = $('#yourtd_id').html().split(','); 
    $.each(data,function(v){ 
     if(v == 'Weekend'){ 
      build+='<span style="color:blue">'+v+'</span>,'; 
     }else{ 
      build+='<span>'+v+'</span>,'; 
     } 

    }); 
$('#yourtd_id').html(build) 

}); 
4

您必須手動添加html標記,或者找到td並使用jQuery對其進行修改。

$('td').html($('td').html().replace('Weekend', '<span>Weekend</span>')); 
$('td span').css('color', 'blue'); 

Something like this fiddle

UPDATE:

new jsFiddle

+0

當有'​​週一,週二,週末'它,它替代爲'星期一,Weekend' –

+0

丈二和尚​​摸不着頭腦對你的實現不同:[的jsfiddle(http://jsfiddle.net/scrimothy/gFppd/1/) – Scrimothy

+0

試試這個'

​​週一,週末​​週一​​星期一週一,週末
' –