使用 JavaScript 跟踪所有点击的元素 [英] Track ALL clicked elements using JavaScript

查看:16
本文介绍了使用 JavaScript 跟踪所有点击的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想跟踪在 HTML 页面上点击的所有元素.我需要一个很好的方法来准确引用哪个元素被点击(这样我以后就可以在一个相同的单独的 HTML 页面上重放这些点击).

I want to track ALL elements that are clicked on a HTML-page. I need a good way to reference exactly which element was clicked (so I will be able to replay the clicks on a identical separate HTML-page later on).

有没有好的方法来引用被点击的元素?

我可以为页面上的每个元素添加唯一的 ID 和类名.但我想肯定还有别的办法?

I could add unique id's and classnames to every single element on the page. But I figure there must be another way?

我将重放点击的 HTML 页面将是相同的.

The HTML-page which I will be replaying the clicks on will be identical.

类似的东西(但更准确的信息是它是哪个元素,也许可以收集)...

Something like this (but more exact information which element it was, maybe that's possible to collect)...

跟踪点击了哪个元素的代码

var arrayWithElements = new Array();

document.onclick = clickListener;

function clickListener(e) {
    var clickedElement;
    if(e == null) {
        clickedElement = event.srcElement;
    } else {
        clickedElement = e.target;
    }
    arrayWithElements.push(clickedElement)
    alert(arrayWithElements);
}

将在相同 HTML 页面上使用的代码

document.someHowGetTheElement().onclick();

推荐答案

我猜你正在寻找这样的东西:

I guess you are looking for something like this:

var arrayWithElements = new Array();

function clickListener(e) 
{   
    var clickedElement=(window.event)
                        ? window.event.srcElement
                        : e.target,
        tags=document.getElementsByTagName(clickedElement.tagName);

    for(var i=0;i<tags.length;++i)
    {
      if(tags[i]==clickedElement)
      {
        arrayWithElements.push({tag:clickedElement.tagName,index:i}); 
        console.log(arrayWithElements);
      }    
    }
}

document.onclick = clickListener;

<小时>

它将在每次点击时存储一个包含元素标签名和索引的对象.因此,您可以使用


It will store on every click an object that contains the tagName of the element and the index. So you may access this element in another "instance" of this document by using

document.getElementsByTagName(item.tag)[item.index]

(其中 item 是 arrayWithElements 的一项)

(where item is an item of arrayWithElements)

演示:http://jsfiddle.net/doktormolle/z2wds/

这篇关于使用 JavaScript 跟踪所有点击的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆