可以获得要在 javascript 上设置的变量

Can get variable to set on javascript

试图使变量__lc.group动态化,以便根据页面的URL设置组号,这是我试过但似乎没有的代码成功了。

不确定为什么它不起作用。这是为了在网站上动态设置实时聊天功能的组变量,这样我就可以为网站的不同页面设置不同的运营商。

if(window.location.href.indexOf("netball") > -1) {
       __lc.group = 1;
    }
if(window.location.href.indexOf("football") > -1) {
       __lc.group = 5;
    }
if(window.location.href.indexOf("basketball") > -1) {
       __lc.group = 2;
    }
if(window.location.href.indexOf("social") > -1) {
       __lc.group = 3;
    }
if(window.location.href.indexOf("fitness") > -1) {
       __lc.group = 6;
    }
if(window.location.href.indexOf("softball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("volleyball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("dodgeball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("american") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("ultimate") > -1) {
       __lc.group = 4;
    }

脚本的完整代码是:

<!-- Start of LiveChat (www.livechatinc.com) code -->
<script type="text/javascript">
var __lc = {};
__lc.license = XXXXX;
if(window.location.href.indexOf("netball") > -1) {
       __lc.group = 1;
    }
if(window.location.href.indexOf("football") > -1) {
       __lc.group = 5;
    }
if(window.location.href.indexOf("basketball") > -1) {
       __lc.group = 2;
    }
if(window.location.href.indexOf("social") > -1) {
       __lc.group = 3;
    }
if(window.location.href.indexOf("fitness") > -1) {
       __lc.group = 6;
    }
if(window.location.href.indexOf("softball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("volleyball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("dodgeball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("american") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("ultimate") > -1) {
       __lc.group = 4;
    }

(function() {
  var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
  lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
<!-- End of LiveChat code -->

这是一种有效且更优雅的处理检查的方法。它定义了一个具有名称和相应数字的对象,然后遍历它并与 url 进行比较。 https://jsfiddle.net/gb2tr4a9/

__lc = {license:123456789}
var categories = {
    netball:4 ,
    football:5,
    basketball:2,
    fiddle:99
}
for (var c in categories) {
    if(window.location.href.indexOf(c) != -1) {
       __lc.group = categories[c]; 
       break;
    }
}    
console.log(__lc);     

响应是一个对象,其中 {group=99}