How to detect Link clicks (text, images, etc) with Javascript?

后端 未结 4 891
盖世英雄少女心
盖世英雄少女心 2020-12-16 00:38

I\'m trying to write a Cross-Browser script that detects when a link is clicked on a page (text link, image, or othwerwise) so that I can show a message or ad (like an inter

4条回答
  •  抹茶落季
    2020-12-16 01:21

    I thought I'd try a non-jQuery (and non-other-library solution too, just for...well, filling a few minutes):

    function clickOrigin(e){
        var target = e.target;
        var tag = [];
        tag.tagType = target.tagName.toLowerCase();
        tag.tagClass = target.className.split(' ');
        tag.id = target.id;
        tag.parent = target.parentNode;
    
        return tag;
    }
    
    var tagsToIdentify = ['img','a'];
    
    document.body.onclick = function(e){
        elem = clickOrigin(e);
    
        for (i=0;i

    JS Fiddle demo.

    Amended the above, to detect img elements nested within an a element (which I think is what you're wanting having re-read your question):

    function clickOrigin(e){
        var target = e.target;
        var tag = [];
        tag.tagType = target.tagName.toLowerCase();
        tag.tagClass = target.className.split(' ');
        tag.id = target.id;
        tag.parent = target.parentNode.tagName.toLowerCase();
    
        return tag;
    }
    
    var tagsToIdentify = ['img','a'];
    
    document.body.onclick = function(e){
        elem = clickOrigin(e);
    
        for (i=0;i

    JS Fiddle demo.

提交回复
热议问题