使用JavaScript更改CSS类时转义正斜杠(&/) [英] Escaping forward slash ("/") while using JavaScript to change CSS class

查看:51
本文介绍了使用JavaScript更改CSS类时转义正斜杠(&/)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于某些条件使用JavaScript添加一些CSS类,但是在我的字符串包含正斜杠(/)的情况下遇到了问题.这就是我的用例

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>

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

I have even tried newProductCode.replace('/','/\'); but while running code, I am facing following error

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

JavaScript error: SyntaxError: unterminated string literal

我无法随产品代码一起更改HTML;对我来说,选择是在JS中进行更改.

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

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

Here is a working js example: JS code

推荐答案

我首先将if语句替换为 indexOf(),然后将 .replace 函数更改为 .replace('/','\\/');

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类时转义正斜杠(&amp;/)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆