簡體   English   中英

如何設置document.getElementById(…)為null按摩為true

[英]How can I set document.getElementById(…) is null massage to true

我的代碼中包含更多document.getElementById,但是當我運行代碼時,只有兩個document.getElementById(ctx1,ctx2)獲取其他值。 我如何才能使其他(在我的情況下為ctx3)返回true,而我卻沒有得到錯誤提示。 這是我的演示代碼:

DEMO

var ctx1=document.getElementById("data1").getContext("2d");     
var ctx2 =document.getElementById("data2").getContext("2d");
var ctx3 =document.getElementById("data3").getContext("2d");

在這種情況下ctx1和ctx2獲得值,但ctx3沒有,這就是為什么我得到document.getElementById(...)在控制台中為空錯誤消息的原因。 我做了一些嘗試,但是都失敗了。

嘗試

1

if(ctx3 === null || 
   ctx3 === undefined) {
    return true;
}   

2

if(document.getElementById("data3")..getContext("2d").value == null){
    return true;
  }

如果具有該ID的元素可能不存在,則需要拆分語句。 您不能這樣做:

// Not this
var ctx3 =document.getElementById("data3").getContext("2d");

...因為document.getElementById("data3")可能返回null ,然后在嘗試將其用於.getContext("2d")遇到錯誤。 所以與其:

var elm3 = document.getElementById("data3");
var ctx3 = elm3 && elm3.getContext("2d");

現在,如果您的文檔中沒有id="data3"元素,則elm3ctx3都將為null 如果有, elm3將指元件和ctx3到2D的上下文。

如果要多次執行此操作,則可以給自己一個函數:

function getOptionalContext(id) {
    var elm = document.getElementById(id);
    return elm && elm.getContext("2d");
}

然后:

var ctx1 = getOptionalContext("data1");
var ctx2 = getOptionalContext("data2");
var ctx3 = getOptionalContext("data3");

旁注:每當您發現自己編寫var1var2var3 ,...時,請考慮使用數組。

如果undefined document.getElementById("data1")( document.getElementById("data1") != null )將給出false 在這種情況下,如果undefined getContext("2d")則可以輕松地跳過它們。 希望這可以幫助。

var ctx1 = ( document.getElementById("data1") != null ) ? ( document.getElementById("data1") != null ).getContext("2d") : null;
var ctx2 = ( document.getElementById("data2") != null ) ? ( document.getElementById("data2") != null ).getContext("2d") : null; 
var ctx3 = ( document.getElementById("data3") != null ) ? ( document.getElementById("data3") != null ).getContext("2d") : null; 

如上面其他人所提到的,發生錯誤是因為如果沒有具有此ID的元素, .getElementById(...)方法將返回null。 而且您不能在null上調用方法,因為它沒有相應的內置類(例如,數字具有Number內置類,因此您可以調用3.0.toFixed()類的方法)。 考慮到TJ Crowder關於使用數組的絕妙建議,這是我的代碼:

var selectors = ["data1", "data2", "data3"];
var contexts = selectors.map(function(selector) {
    var elem = document.getElementById(selector);
    return elem ? elem.getContext("2d") : true;
});

這將返回一個上下文數組(如果不存在元素,則在數組中其上下文的位置出現true

暫無
暫無

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

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