小编典典

在Firefox中运行的event.path是未定义的

javascript

event.path[n].id在Firefox中运行时,出现此错误。它可以在其他浏览器中使用。

event.path未定义


阅读 783

收藏
2020-05-01

共1个答案

小编典典

对象的path属性Event是非标准的。标准等效项是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和Edge都不支持pathcomposedPath。Firefox支持composedPath。Chrome支持path(这是Google的原始想法)和composedPath

因此,我认为您无法直接在IE11或Edge上获取路径信息。你可以很明显,获得通过的路径e.target.parentNode和每个随后parentNode,这
通常 是相同的,但当然点的path/ composedPath是,它并不 总是
该事件被触发后,相同的(如果事情修改DOM但在此之前你的处理器接到电话)。

2020-05-01