How do you catch a click event with plain Javascript?

后端 未结 6 1686
挽巷
挽巷 2021-01-31 10:11

I know that when using jQuery you can do $(\'element\').click(); to catch the click event of an HTML element, but how do you do that with plain Javascript?

6条回答
  •  轮回少年
    2021-01-31 10:21

    I usaly create a kind of global event handler, very powerful, you can capture className, of the event "types" nodeTypes, you name it, i hope people will find this useul

    document.onclick = eventRef
    
    function eventRef(evt) {
        var han;
        evt || (evt = window.event);
    
        if (evt) {
            var elem = evt.target ? han = evt.target : evt.srcElement && (han = evt.srcElement);
    
             // evt.type could be, mouseup, mousedown...
            // elem.id is the id or the element
            // elem.className is the class name of the element
            // you could nest expression, use substrings to extract part of a className
            if (evt.type=="click" && elem.id == "gotit" || elem.className == "someClassName") {  
                alert(elem.id);
            }
        }
    }
    

提交回复
热议问题