如何将jquery代码与类似的函数结合起来?

如何将jquery代码与类似的函数结合起来?,jquery,css,Jquery,Css,是否可以减少代码或使用相同功能重新创建类似代码:。谢谢 $(".addcolor:contains('red')").html(function(_, html) { return html.replace(/(red)/g, '<span class="red">$1</span>') }); $(".addcolor:contains('blue')").html(function(_, html) { return html.replace(/(bl

是否可以减少代码或使用相同功能重新创建类似代码:。
谢谢

$(".addcolor:contains('red')").html(function(_, html) {
   return  html.replace(/(red)/g, '<span class="red">$1</span>')
});
$(".addcolor:contains('blue')").html(function(_, html) {
   return  html.replace(/(blue)/g, '<span class="blue">$1</span>')
});
$(".addcolor:contains('green')").html(function(_, html) {
   return  html.replace(/(green)/g, '<span class="green">$1</span>')
});
$(“.addcolor:contains('red')”).html(函数(\ux,html){
返回html.replace(/(红色)/g,“$1”)
});
$(“.addcolor:contains('blue')”).html(函数(\ux,html){
返回html.replace(/(蓝色)/g,“$1”)
});
$(“.addcolor:contains('green')”).html(函数(\ux,html){
返回html.replace(/(绿色)/g,“$1”)
});

代码的功能是用span替换特定文本。如何将css直接应用到jquery代码中?

虽然我并不擅长Javascript正则表达式,但我的技巧如下:

基本上,我将重复部分作为一个函数,然后用变量声明它

function addColor(object) {
    $(".addcolor:contains(" + object +")").html(function(_, html) {
        var re = new RegExp(object,"g");
        return  html.replace(re, '<span class="' + object +'">' + object + '</span>')
    });
}

addColor('red');
addColor('blue');
addColor('green');
函数addColor(对象){
$(“.addcolor:contains(“+object+”)).html(函数(\ux,html){
var re=新的RegExp(对象,“g”);
返回html.replace(re,“+对象+”)
});
}
addColor(“红色”);
addColor(“蓝色”);
添加颜色(“绿色”);

使用数组存储所有颜色值并创建正则表达式:

var arr = ['red','green','blue'];

for(i=0;i<arr.length;i++){
$(".addcolor").html(function(_, html) {

    var regex = new RegExp("("+arr[i]+")","g");
    htmla = '<span class="'+arr[i]+'">$1</span>';

   return  html.replace(regex, htmla);
});
}
var-arr=[“红色”、“绿色”、“蓝色”];

对于(i=0;i

谢谢,先生,我认为这个更好。有可能在jquery代码中包含css吗?与其包装它,不如直接应用颜色。如果它们事先被包装在某个东西中,您可以直接应用颜色。因为它们是字符串的一部分,所以不可能直接将它们作为@austined样式eveloper说过,您只能使用jQuery设置元素的样式,不能使用字符串。这是另一个很好的答案。我真的说不出哪一个更好。您甚至不需要选择器中的
:contains
,您只需删除它即可。@DarkAshelin感谢您的更正,我从原始代码开始,所以错过了它。