Javascript 如何分割字符串并为每个字符串设置颜色?
我有一个字符串,我喜欢你从h2元素中得到:我喜欢你 现在我想把它分开,在两个空格中为每个单词着色。如何更改标记中每个文本的颜色。 我可以对每种颜色使用数组[I]Javascript 如何分割字符串并为每个字符串设置颜色?,javascript,jquery,Javascript,Jquery,我有一个字符串,我喜欢你从h2元素中得到:我喜欢你 现在我想把它分开,在两个空格中为每个单词着色。如何更改标记中每个文本的颜色。 我可以对每种颜色使用数组[I] array[1], color:red array[2], color:green array[3], color:blue 加载时颜色会发生变化。谢谢你的建议 试试看 var array = ['red', 'green', 'blue']; $('#demo').html(function(idx, html){ ret
array[1], color:red
array[2], color:green
array[3], color:blue
加载时颜色会发生变化。谢谢你的建议 试试看
var array = ['red', 'green', 'blue'];
$('#demo').html(function(idx, html){
return $.map(html.split(/\s/), function(value, idx){
if(idx < array.length){
return '<span style="color: ' + array[idx] + '">' + value + '</span>'
} else {
return value
}
}).join(' ');
})
演示:试试看
var array = ['red', 'green', 'blue'];
$('#demo').html(function(idx, html){
return $.map(html.split(/\s/), function(value, idx){
if(idx < array.length){
return '<span style="color: ' + array[idx] + '">' + value + '</span>'
} else {
return value
}
}).join(' ');
})
演示:一个建议,直到你给出一个更好的例子来说明你在寻找什么
$(document).ready(function(){
$.each(array, function(id,value) {
var color = value.strreplace('color:','');
$('#'+id).css('color', color);
});
});
一个建议,直到你给出一个更好的例子,你在寻找什么
$(document).ready(function(){
$.each(array, function(id,value) {
var color = value.strreplace('color:','');
$('#'+id).css('color', color);
});
});
通过简单的Javascript
function str_split (string, split_length) {
if (split_length === null) {
split_length = 1;
}
if (string === null || split_length < 1) {
return false;
}
string += '';
var chunks = [],
pos = 0,
len = string.length;
while (pos < len) {
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
通过简单的Javascript
function str_split (string, split_length) {
if (split_length === null) {
split_length = 1;
}
if (string === null || split_length < 1) {
return false;
}
string += '';
var chunks = [],
pos = 0,
len = string.length;
while (pos < len) {
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
谢谢你的帮助。谢谢你的帮助。谢谢你的帮助。我会把你的答案投给最好的。祝你快乐。谢谢你的帮助。我会把你的答案投给最好的。祝你快乐。