JS event listener for a type of element?

前端 未结 5 1686
野趣味
野趣味 2021-01-22 18:47

Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element

相关标签:
5条回答
  • 2021-01-22 19:09

    I'd just select all the elements on the page and add eventListeners on them like so:

    function addListeners(elementType, eventType, callback) {
        Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
            el.addEventListener(eventType, callback, false);
        });
    }
    

    Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.

    Here's an example: https://jsfiddle.net/a7en4d4s/

    0 讨论(0)
  • 2021-01-22 19:10

    I assume that you are looking for code along these lines:

    var paras = document.getElementsByTagName("p");
    
    // Loop through elements. 
    for(var i = 0; i < paras.length; i++) {
        // Add listener.
        paras[i].addEventListener("click",
            function() { 
                // Execute function.
            }, false);
    }
    
    0 讨论(0)
  • 2021-01-22 19:11

    Look at this JSFiddle, and see if it works for you

    <span>Click Yes</span><br/><br/>
    <span>Click No</span><br/><br/>
    <a>Clicked: <b id="result"></b></a>
    <script>
        $("span").click(function(){
        var a = $(this).html();
        $("#result").html(a);
        });
    </script>
    
    0 讨论(0)
  • 2021-01-22 19:17

    the easiest answer would be using addEventListener() if you want a specific html tag just like what i wanted in my question then you'll find the answer there ill paraphrase it here too add this

    <script>
        document.addEventListener("click", function(e){
       //your desired nodeName like : DIV , SPAN , LI etc
           if(e.target && e.target.nodeName== 'DIV')
           //add a function below to trigger 
           {alert('bingo')}
        });
    
    </script>

    to the end of your document by the way don't forget to use uppercase nodeNames or just put a toLowerCase() before it. cheers :)

    0 讨论(0)
  • 2021-01-22 19:18

    Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a <span> inside a <p>, clicking the span won't trigger the click in the paragraph.

    document.addEventListener("click", function (eventArgs) {
        var target = eventArgs.target;
        var elementToLookFor = "p";
        while (target !== null) {
            if (target.tagName.toLowerCase() === elementToLookFor) {
                // Do magic stuff with the paragraph
                console.log(target);
            }
            target = target.parentElement;
        }
    });
    

    This technique is called "event delegation."

    Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.

    <p>
        Hey,
        <p>there!</p>
    </p>
    

    Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.

    0 讨论(0)
提交回复
热议问题