簡體   English   中英

如何防止一個JavaScript文件與另一個文件沖突?

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

我正在開發的網站上運行2個腳本,一個腳本與另一個腳本沖突

第二個僅在第一個丟失時才起作用。所以我不知道問題出在哪里。

您可以看到此鏈接。

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

在此頁面中,預覽標題位於第3部分,在該部分中,如果單擊任何標題,則會出現燈箱,但左側菜單下拉腳本不起作用,並且與燈箱腳本沖突。

根據腳本的大小,使用命名空間通常是消除沖突的好方法。

兩種最常見的引入方式是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM