gpt4 book ai didi

javascript - event.path 未定义在 Firefox 中运行

转载 作者:IT老高 更新时间:2023-10-28 21:58:41 25 4
gpt4 key购买 nike

当我在 Firefox 中运行 event.path[n].id 时,我收到此错误。它适用于其他浏览器。

event.path undefined

最佳答案

Event 对象的 path 属性是非标准的。标准等效值为 composedPath ,这是一种方法。但它是新的。

所以你可能想尝试回退到那个,例如:

var path = event.path || (event.composedPath && event.composedPath());
if (path) {
// You got some path information
} else {
// This browser doesn't supply path information
}

如果浏览器不提供路径信息,显然它不会为您提供路径信息,但它允许旧方式和新的标准方式,因此会尽其所能地跨浏览器。

例子:

document.getElementById("target").addEventListener("click", function(e) {
// Just for demonstration purposes
if (e.path) {
if (e.composedPath) {
console.log("Supports `path` and `composedPath`");
} else {
console.log("Supports `path` but not `composedPath`");
}
} else if (e.composedPath) {
console.log("Supports `composedPath` (but not `path`)");
} else {
console.log("Supports neither `path` nor `composedPath`");
}

// Per the above, get the path if we can
var path = e.path || (e.composedPath && e.composedPath());

// Show it if we got it
if (path) {
console.log("Path (" + path.length + ")");
Array.prototype.forEach.call(
path,
function(entry) {
console.log(entry.nodeName);
}
);
}
}, false);
<div id="target">Click me</div>

在我的测试中(2018 年 5 月更新),IE11 和 Legacy Edge(v44 或更早版本,在从 v79 开始的 Chromium 更新之前)都不支持 pathcomposedPath . Firefox 支持 composedPath。 Chrome 支持 path(这是 Google 最初的想法)和 composedPathAccording to MDN自 2020 年 1 月起,除 IE11 之外的所有主要浏览器的最新版本都支持 composedPath

所以我认为您无法直接在 IE11(或 Legacy Edge)上获取路径信息。显然,您可以通过 e.target.parentNode 和每个后续 parentNode 获取路径,这通常是相同的,但当然是path/composedPath 的意义在于它并不 总是 相同(如果在触发事件之后但在调用您的处理程序之前修改了 DOM )。

关于javascript - event.path 未定义在 Firefox 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com