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

How can I prevent a JavaScript file from conflicting with another?

本文关键字:文件 另一个 冲突 JavaScript 一个 何防止      更新时间:2023-09-26

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

第二个只有在第一个缺失的情况下才会工作。所以我不知道问题出在哪里。

你可以看到这个链接。

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

在这个页面有预览标题是在第三部分,在那部分,如果你点击任何标题灯箱将出现,但左侧菜单下拉脚本不工作,并与灯箱脚本冲突。

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

最常见的两种介绍方式是:

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*/}
};

然后调用命名对象(例如namespace)内的函数

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*/};
  }
}