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

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

问题描述

我想跟踪在HTML页面上单击的所有元素.我需要一种很好的方法来完全引用被单击的夹心元素(这样以后我就可以在相同的单独HTML页面上重播这些单击).

I want to track ALL elements that are clicked on a HTML-page. I need a good way to reference exactly wich 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 a nother way?

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

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

有些东西可以了(但是可以提供更确切的信息,也许可以收集)...

Something lite this (but more exact information wich 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;


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


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天全站免登陆