簡體   English   中英

遇到未定義的元素時,我可以使javascript運行函數嗎?

[英]Can I make javascript run a function when it encounters an undefined element?

我正在維護一個非常老的Web窗體應用程序,該應用程序與IE6兼容的javascript粘合在一起。 這意味着可以在JS中訪問元素,而無需先初始化。

我的意思是,使用此方法是“有效的”:

txtIngredient.value = 'potato';

為了使其在新的瀏覽器(例如Chrome,Firefox等)中運行,此代碼變為:

document.getElementById('txtIngredient').value = 'potato';

顯然,Chrome,Firefox等在遇到前一個語句時會拋出未定義的錯誤,並且由於引發的異常而導致JS停止執行。

目前,我正在遍歷代碼並進行移植,使其看起來更像后者,但是我想知道是否可以編寫一個錯誤處理程序來處理未定義的錯誤,這些錯誤將在發生這種情況時捕獲,然后以某種方式捕獲返回該元素(如果它在DOM中找到)並重新嘗試該語句? 如果這樣,將節省大量工作。

編輯:例如:

此代碼無法正常工作:

function ShrinkDetails() {
        document.Form1.btnExpand.value = "+ Dispense Details";
        trDateDispensed.style.display = "none";
        trDuration.style.display = "none";
        trStartDate.style.display = "none";
        trRepeats.style.display = "none";
        trQuantity.style.display = "none";
    }

Chrome等在document.Form1上引發未定義的錯誤。

這段代碼可以工作:

function ShrinkDetails() {
        document.getElementById('btnExpand').value = "+ Dispense Details";
        document.getElementById('trDateDispensed').style.display = "none";
        document.getElementById('trDuration').style.display = "none";
        document.getElementById('trStartDate').style.display = "none";
        document.getElementById('trRepeats').style.display = "none";
        document.getElementById('trQuantity').style.display = "none";
    }

聽起來您需要對要獲得的參考錯誤進行嘗試/捕獲?

try {
   var myVar = txtIngredient;
} catch (e) {
  if (e instanceof ReferenceError) {
  // code here
}

暫無
暫無

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

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