zoukankan      html  css  js  c++  java
  • [Javascript] event.target.closest(selector)

    The Event Delegation Pattern

    Event delegation is a simple, but powerful leveraging of the DOM event system which allows for easier adding of functionality to dynamically created content; as well as being an interesting performance optimization.

    Idea is you just need to add one event listener to the partent DOM element, instead of add one event listener for each child element.

    For example, 

    <Child>
        <button>Click</button>
    </Child>
    child,addEventListener(
        'click',
        function onClick(event) {
            if (event.target instanceof Element && event.target.tagName === "Button") {
         addButton();
    }})

    Problem is if you put "click" into a Span

    <Child>
        <button><span>Click</span></button>
    </Child>

    Previous code won't work, work around can be:

    child,addEventListener(
        'click',
        function onClick(event) {
            if (event.target instanceof Element && event.target.closest('button') === "Button") {
         addButton();
    }})

    The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

  • 相关阅读:
    1136.NumberSteps
    1134.密码翻译
    1133.学分绩点
    1131.合唱队形
    1132.与7无关的数
    1130.日志排序
    Educational Codeforces Round 41 (Rated for Div. 2)
    Codeforces Round #378 (Div. 2) F
    Codeforces Round #290 (Div. 2)
    牛客网练习13 乌龟跑步
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15162112.html
Copyright © 2011-2022 走看看