【问题标题】:How to get the exact location of an html element [duplicate]如何获取html元素的确切位置[重复]
【发布时间】:2017-07-18 23:15:42
【问题描述】:

我想得到一个html元素的准确位置,并输出那个元素的地址,逻辑是这样的。

<div id="foo">
   <article>
       <div>
          <p>you found me</p>
       </div>
   </article>
<div>

这就是示例 html,现在假设用户单击了该标记上的某些内容,在这种情况下,假设用户单击了“p”标签。如何编写我的 JavaScript 来输出那个“p”标签的地址。

     function getAddress(){
         // code here
         console.log('the user click the ')
         console.log(address)
     }

期望的输出:

      // Console
      log: the user click the
      log: #foo > article > div > p

【问题讨论】:

  • 任何搜索算法背后的逻辑是什么?或者你想回溯直到父母带有id?
  • @omi 基本上我想回溯直到父母带有 id

标签: javascript jquery html


【解决方案1】:

类似这样的:

$(document).ready(function () {
    var path = '';
    $('#foo').on('click', '*', function (e) {
        path = $(this).prop("tagName");
        $(this).parents().each(function () {
            path = $(this).prop("tagName") + ' > ' + path;
        });
        alert(path);
        e.stopPropagation();
    });
})

Sample fiddle

更新

添加id 属性:

$(document).ready(function () {
    var path = '';
    $('#foo').on('click', '*', function (e) {
        path = $(this).prop("tagName").toLowerCase();
        $(this).parents().each(function () {
            let id = $(this).attr('id');
            path = $(this).prop("tagName").toLowerCase() + (typeof id != 'undefined' ? '#'+id : '') + ' > ' + path;
        });
        alert(path);
        e.stopPropagation();
    });
});

Updated fiddle

大写标记名称更新

基于MDN

在 XML(和基于 XML 的语言,如 XHTML)中,tagName 保留大小写。在标记为 HTML 文档的 DOM 树中的 HTML 元素上,tagName 以大写形式返回元素名称。 tagName 的值与 nodeName 的值相同。

来源:https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

【讨论】:

  • 这正是我想要的,但为什么字符串都是大写的?
  • @MarvenWilsonSDonque,请参阅我的更新以获取有关大写标签名称问题的答案。
  • @MarvenWilsonSDonque,不知道您为什么将我的回复标记为答案,然后又改变了主意。说了这么多“谢谢”:(
  • @Frank Fajardo 对不起,我很困惑,我以为我标记了你的答案,你的代码正是我要找的,非常感谢..
  • @Frank Fajardo 我很困惑,对不起,我没有改变主意..
【解决方案2】:

我正在使用 jQuery 并创建了这段代码 sn-p。点击P标签

jQuery("p").click(function(){
  var parentEls = $(this).parents()
  .map(function() {
    return this.tagName;
  })
  .get()
  .join(">");
  alert(parentEls);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
   <article>
       <div>
          <p>you found me</p>
       </div>
   </article>
<div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多