使用 JavaScript 更改 CSS 类时转义正斜杠(“/”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36469397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:07:46  来源:igfitidea点击:

Escaping forward slash ("/") while using JavaScript to change CSS class

javascriptjqueryhtml

提问by Umesh Awasthi

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

我需要使用 JavaScript 根据某些条件添加一些 CSS 类,但如果我的字符串包含正斜杠 ( /),则会面临问题。这就是我的用例

<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

我什至尝试过, newProductCode.replace('/','/\');但是在运行代码时,我面临以下错误

JavaScript error: SyntaxError: unterminated string literal

JavaScript 错误:SyntaxError:未终止的字符串文字

I can not change HTML along with product code; the option for me is to change it in JS.

我不能随产品代码一起更改 HTML;我的选择是在 JS 中更改它。

Here is a working js example: JS code

这是一个有效的 js 示例:JS 代码

采纳答案by Pugazh

I have first replaced the if statement with indexOf()and changed the .replacefunction as .replace('/', '\\/');

我首先用 if 语句替换indexOf()并将.replace函数更改为.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>

回答by hargasinski

@Pugazh probably has the correct way of doing it, but you could just isolate the stringin "by searching using an attributein jQuery. Here's a linkto the API documentation. It avoids having to do the replace altogether. It's a hacky way of doing it.

@Pugazh可能有这样做的正确的方式,但你可以很孤立string"通过使用搜索attributejQuery中。这是API 文档的链接。它避免了必须完全替换。这是一种hacky的方式。

var newProductCode = '121NM/L';
$('[id="div_product-size-icon-'+newProductCode+'"]').addClass('active');