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>
Event delegation, the most basic code is as follows!
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!
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/