在使用JavaScript更改CSS类时转义正斜杠(“/”) [英] Escaping forward slash ("/") while using JavaScript to change CSS class
问题描述
我需要使用JavaScript基于某些条件添加一些CSS类,但是如果我的字符串包含正斜杠( /
),则会面临问题。这就是我的用例
< div id =div_product-size-icon-121NM / Lclass =禁用>< / DIV>
< script>
var newProductCode ='121NM / L';
if(newProductCode.contains('/')){
newProductCode = newProductCode.replace('/','/ \\ // //');
$('#'+'div_product-size-icon - '+ newProductCode).addClass('active');
}
< / script>
我甚至试过 newProductCode.replace('/','/ \\ \\');
但是在运行代码时,我面临以下错误:
lockquote
JavaScript错误:SyntaxError:未终止的字符串字面值
我不能随产品代码一起更改HTML;我的选择是在JS中进行更改。
以下是一个可用的js示例: JS代码
我先用 indexOf()
并将 .replace
函数更改为 .replace('/','\\ / ');
var newProductCode ='121NM / L'; if(newProductCode.indexOf('/') > 0){alert('一旦你点击确定,文字就会消失!!'); newProductCode = newProductCode.replace('/','\\ /'); $('#'+'div_product-size-icon-'+ newProductCode).addClass('active');}
div.active {display:none;}
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script> < div id =div_product-size-icon-121NM / Lclass =disabled>一些文字在这里< / div>
div>
I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash (/
). This is what my use case is
<div id="div_product-size-icon-121NM/L" class="disabled"></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','/\//');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>
I have even tried newProductCode.replace('/','/\');
but while running code, I am facing following error
JavaScript error: SyntaxError: unterminated string literal
I can not change HTML along with product code; the option for me is to change it in JS.
Here is a working js example: JS code
I have first replaced the if statement with indexOf()
and changed the .replace
function as .replace('/', '\\/');
var newProductCode = '121NM/L';
if (newProductCode.indexOf('/') > 0) {
alert('Once you click OK, the text will disappear!!');
newProductCode = newProductCode.replace('/', '\\/');
$('#' + 'div_product-size-icon-' + newProductCode).addClass('active');
}
div.active {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_product-size-icon-121NM/L" class="disabled">Some text here</div>
这篇关于在使用JavaScript更改CSS类时转义正斜杠(“/”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!