这适用于 Chrome:
document.querySelectorAll('input[type="text"]').forEach(elt => {
elt.addEventListener("change", e => {
localStorage.setItem(e.path[0].name, e.path[0].value);
});
});
但在 Firefox 上生成此内容:
TypeError: e.path is undefined
e.path[0]
的跨浏览器等效项是什么?
最佳答案
Firefox 等效项是 e.composedPath()
document.querySelectorAll('input[type="text"]').forEach(elt => {
elt.addEventListener("change", e => {
let path = e.path || e.composedPath()
localStorage.setItem(path[0]?.name, path[0]?.value);
});
});
如果浏览器不支持这两者,它仍然不会给出错误,但会因为使用path?.property而设置 Item undefined:undefined
关于javascript - 如何在addEventListener跨浏览器中使用e.path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61445948/