类html用符号替换字符串

时间:2019-03-22 14:10:27

标签: jquery css replace

如何将包含符号的字符串替换为CSS类?

HTML

<body>
    <div id="container">
       <div class="class-one class-two"></div>
    </div>
</body>

JQUERY

p= '@.class-two';

$('#container').find('.class-one' + ReplaceString(p)).css("background-color", "red");

alert(ReplaceString(p)); // \@\.class-two

function ReplaceString (mystring) {
        return mystring.replace( /(:|\.|\[|\]|,|=|@)/g, "\\" );
}

1 个答案:

答案 0 :(得分:0)

我认为,您正在为jQuery选择器而苦苦挣扎。 您的替补确实适合我。我刚刚删除了反斜杠作为替换:

function ReplaceString (mystring) {
        return mystring.replace( /(:|\.|\[|\]|,|=|@)/g, "" );
}

然后,您必须修改jQuery选择器。如果您有多个班级,请用逗号将它们分开:

$('#container').find('.class-one,.' + ReplaceString(p)).css("background-color", "red");

这是我尝试的完整代码。对我来说效果很好:

p= '@.class-two';

$('#container').find('.class-one,.' + ReplaceString(p)).css("background-color", "red");

function ReplaceString (mystring) {
        return mystring.replace( /(:|\.|\[|\]|,|=|@)/g, "" );
}

查看小提琴:https://jsfiddle.net/dnsnx/h3ajdmge/