如何防止JavaScript文件与另一个文件冲突?

时间:2013-05-06 13:08:29

标签: javascript

我正在开发的网站上运行2个脚本,其中一个与另一个

冲突

第二个只有在缺少第一个时才会起作用。所以我不知道问题是什么。

您可以看到此链接。

http://electionsguru.in/mfc_new/newkursplan.php?id_shop=35

在此页面中,预览标题位于第3部分,如果单击任何标题,则该部分将出现,但左侧菜单下拉脚本不起作用且与灯箱脚本冲突。

1 个答案:

答案 0 :(得分:1)

根据脚本的大小,使用命名空间通常是消除冲突的好方法。

引入的两种最常见的方式是:

var ns = ns || {};
ns.ondocready = function(){/*your declaration here*/};
ns.onsomeotherfunct = function(arg){/*your declaration here*/};

var othernamespace = {
  publicvar:'something available to all namespaced functions',
  ondocready:function(){/*your declaration here*/},
  someotherfunction:function(arg){/*your declaration here*/}
};

然后调用命名对象(例如命名空间)中的函数

ns.ondocready();
othernamespace.someotherfunction('test');
othernamespace.publicvar = 'available to functions within namespace by referencing with "this" keyword';

唯一需要注意的是,当使用“this”关键字引用对象中的变量或函数时,它可能与jQuery“this”关键字冲突。要避免,请在函数中设置变量。

var ns1 = {
  islive : false,
  docheck : function(){
    var ns = this; //--set scope to variable for access to prevent conflict within jQuery functions where this keyword is referenced
    if(this.islive){/*conditional declaration*/};
  }
}