javascript - How to use native JS listening to event bind more loaded tags
天蓬老师
天蓬老师 2017-06-26 10:56:02
0
3
799

Some projects use JS templates, but the tags in the template are html tags whose strings are not running normally. After event binding is performed on the tags loaded at the beginning of the page, the tags loaded later will be loaded later, unless jQuery is used. , I can't figure out what to use to listen and then implement event binding.
The project stipulates that frameworks such as jQuery and zetpo cannot be used, so I would like to ask, as in the question.

<p class="p">标签p</p>
<script>
    var ps = document.querySelectorAll('.p');
    for (var i = 0; i < ps.length; i++) {
        ps[i].addEventListener('click', function(){
            var that = this;
            console.log(that.innerText);
        })
    }
</script>
<script type="template">
    <p class="p">字符串标签p</p>
</script>
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
巴扎黑

Event delegation, the most basic code is as follows!

window.onload = function(){
  document.onclick = function(ev){
    var ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    if(target.className.toLowerCase() === 'p'){
         console.log(this.innerHTML);
    }
  }
}

Document can be replaced by other elements, but the replaced element must exist from the beginning! It cannot be added dynamically after the page is loaded!

ringa_lee

Usually event delegation

漂亮男人

Event delegation is correct. To put it bluntly, it uses DOM event bubbling. @Waiting for You’s answer explains the principle and solves the basic problem. However, there are still some limitations in practical applications. It can only process the element that was finally clicked, rather than the elements encountered during the bubbling process.

I wrote an example of the bubbling process: https://jsfiddle.net/4L7p5drb/1/

const outer = document.getElementById("outer");

/**
 * host,已经存在的元素,用来绑定代理事件的
 * evnetName,事件名称
 * predicate,用来判断代理事件的目标对象 (el: HtmlElement) => bool 类型
 * handler,处理函数,(e: Event) => any 类型,其 this 指向实际目标对象
 */
function proxyListener(host, eventName, predicate, handler) {
    host.addEventListener(eventName, e => {
        let target = e.target || e.srcElement;
        while (target !== host) {
            if (predicate(target)) {
                handler.call(target, e);
                // 这里没有 break 主要是考虑一多层都拥有可判断为 true 的对象呢
                // 可以根据实际需要加 break;
            }
            target = target.parentNode || target.parentElement;
        }
    });
}

proxyListener(outer, "click",
    t => t.classList.contains("middle"),
    function(e) {
        console.log("hit", this);
    });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!