如何将包含符号的字符串替换为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, "\\" );
}
答案 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, "" );
}