【问题标题】:How can I find the relative xpath of anything that i click page (Javascript)如何找到我单击页面的任何内容的相对 xpath (Javascript)
【发布时间】:2019-11-25 15:40:44
【问题描述】:

我有一个页面,我想使用 javascript 来获取我在页面上单击的任何元素的相对 xpath.. 但这段代码似乎不起作用。如何使用此代码给我相对 xpath?

function getElementXPath(elt, theClass) {
  var path = "";
  for (; elt && elt.nodeType == 1; elt = elt.parentNode) {
    idx = getElementIdx(elt);
    xname = elt.tagName;
    if (idx > 1) xname += "[" + idx + "]";
    path = "/" + xname + path;
  }

  return path;
}

function getElementIdx(elt) {
  var count = 1;
  for (var sib = elt.previousSibling; sib; sib = sib.previousSibling) {
    if (sib.nodeType == 1 && sib.tagName == elt.tagName) count++
  }

  return count;
}
document.addEventListener("click", (e) => {
  document.querySelector("#xpath").value = getElementXPath(e.target);

  alert(e.target.this.id + getElementXPath(e.target));
})

【问题讨论】:

    标签: javascript php jquery xpath


    【解决方案1】:

    您可以在单击文档时发出的事件对象上使用 clientX/clientY。这是一个你可以使用的句柄小函数:

    const getCursorPosition = event => {
      return { 
        x: event.clientX,
        y: event.clientY
      }
    }
    
    window.addEventListener('click', e => {
      const position = getCursorPosition(e)
      console.log('click position: ', position)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多