[英]JS - document.querySelector() || document.querySelector() gives type error
我有以下代碼(虛擬):
myFunction(document.querySelector('[data-param="param1"]').textContent || document.querySelector('[data-param="param2"]').textContent);
應該做的是如果param1
存在,則使用那個,否則,通過利用falsy
的使用來使用param2
。 我知道這不是最好的使用方法(請參閱此處),但這是我根據自己的情況想出的方法。
我試圖制作一個jsfiddle來證明這一點; 但是,錯誤是錯誤的,盡管這可能只是控制台中的不同措辭,因為我使用的是兩種不同的瀏覽器(不要問)。
在 Fire bug 中,它說:
類型錯誤:document.querySelector(...) 為空
在 Chrome 中它說:
類型錯誤:無法讀取 null 的屬性“your-property-here”
我以為我可以使用document.getElementById('param1') || document.getElementById('param2')
document.getElementById('param1') || document.getElementById('param2')
但jsfiddle給出的內容似乎不適用於querySelector
或getElementById
。
我在文檔上找不到任何關於這個的東西,我的谷歌搜索也沒有找到任何東西......
這是一個功能還是一個錯誤? 是否有一種方法可以利用querySelector
(或getElementById1
等)上的falsy
值? 做我想做的事情的最佳方法是什么?
您看到錯誤的原因是您的第一個查詢返回 null,因此它沒有屬性數據集。 試試這個:
(document.querySelector('[data-example="example1"]') || document.querySelector('[data-example="example2"]')).dataset.example
現在,如果document.querySelector('[data-example="example1"]')
返回 null,它將嘗試document.querySelector('[data-example="example2"]')
代替。 不過您應該知道,如果兩個查詢都返回 null,您仍然會收到錯誤消息。
關於您的案例,javascript 中沒有錯誤。 這是您代碼中的錯誤。 因為如果提供的參數與document
中的任何元素都不匹配,則document.querySelector()
或getElementById
將返回null
。 因此null.anything
會拋出錯誤。 您可以像下面這樣重寫代碼以避免此類錯誤,
var res = (document.getElementById('id1') || document.getElementById('id2')).id;
並且在這里,如果id1
或id2
都不匹配任何內容,則會引發相同的錯誤。 你也可以像下面那樣處理這種情況,
var res = (document.getElementById('id1') || document.getElementById('id2') || {}).id;
現在在這種情況下,如果沒有匹配項,則res
將為undefined
。
可能您應該按如下方式更正代碼;
// data attribute:
var elm1 = document.querySelector('[data-example="example1"]') || document.querySelector('[data-example="example2"]');
elm2 = document.getElementById('id1') || document.getElementById('id2');
document.getElementsByTagName('BUTTON')[0].addEventListener('click', function(e) {
try {
e.target.className += elm1.dataset.example;
} catch(e) {
document.getElementById('log').innerHTML += '<div>' + e + new Date() + '</div>';
}
});
// id:
document.getElementsByTagName('BUTTON')[1].addEventListener('click', function(e) {
try {
e.target.className += elm2.id
} catch(e) {
document.getElementById('log').innerHTML += '<div>' + e + new Date() + '</div>';
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.