Track ALL clicked elements using JavaScript

故事扮演 提交于 2020-05-09 19:15:28

问题


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).

Is there a good way to reference wich element that was clicked?

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

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)...

Code to track wich element that was clicked

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);
}

Code that will be used on a identical HTML-page

document.someHowGetTheElement().onclick();

回答1:


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]

(where item is an item of arrayWithElements)

Demo: http://jsfiddle.net/doktormolle/z2wds/




回答2:


You can use this related question. In other words, a good way to know which element was clicked without adding IDs all over the place is to use jquery's .cssSelectorAsString() method. For example:

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

See also: Get unique selector of element in Jquery



来源:https://stackoverflow.com/questions/9509231/track-all-clicked-elements-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!