我有一個事件偵聽器,用于click確定document路徑composedPath中的任何內容是否包含某個屬性。
如果路徑中的某些內容確實包含我所聽的屬性,那么一切都很好,一切正常。
但是,如果路徑中的某些內容不包含我偵聽的屬性,則會引發例外:
“未捕獲的 TypeError:el.hasAttribute 不是函式”
這是一個顯示這個的小提琴:
document.addEventListener('click', (event) => {
const includesAttribute = event.composedPath().some((el) => el.hasAttribute('my-attribute'));
console.log(`has attribute: ${includesAttribute}`);
});
<button my-attribute>click me, I log true and work fine</button>
<br/>
<button other-attribute>click me, I throw an exception because I don't have the attribute</button>
為什么只有當屬性不存在時才會得到例外?該方法不應該hasAttribute始終可用嗎?
uj5u.com熱心網友回復:
因為document沒有辦法getAttribute。當它沒有找到任何東西時,您的電話some一直在進行;document請參閱此處的日志記錄nodeName:
顯示代碼片段
document.addEventListener('click', (event) => {
const includesAttribute = event.composedPath().some((el) => {
console.log(el.nodeName);
return el.hasAttribute('my-attribute');
});
console.log(`has attribute: ${includesAttribute}`);
});
<button my-attribute>click me, I log true and work fine</button>
<br/>
<button other-attribute>click me, I throw an exception but now you can see why</button>
只需添加一個守衛:
document.addEventListener('click', (event) => {
const includesAttribute = event.composedPath().some((el) => el.hasAttribute && el.hasAttribute('my-attribute'));
console.log(`has attribute: ${includesAttribute}`);
});
顯示代碼片段
document.addEventListener('click', (event) => {
const includesAttribute = event.composedPath().some((el) => el.hasAttribute && el.hasAttribute('my-attribute'));
console.log(`has attribute: ${includesAttribute}`);
});
<button my-attribute>click me, I log true and work fine</button>
<br/>
<button other-attribute>click me, I do not throw an exception anymore</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465583.html
上一篇:拆分一列熊貓的內容
