Js binds events to dynamically generated elements

for (let i=0;i<10;iPP){
       const html = `<webview src="http://www.github.com">i</webview>`;
       $(".container").append(html)
    }
    const webview = document.querySelectorAll("webview")
    webview[0].addEventListener("console-message", e => {
        console.log(e.message);
        if(e.message.indexOf("")!==-1){
            alert("")
        }
    });

you need to traverse one or more webview tags on a page. There is an event called console-message, that returns some strings from time to time, so I want to monitor this event in real time. If I know the number of webview tags in advance, this is not a problem, but this tag may be N, then I have to create N addEventListener monitoring events. There is no train of thought at all. Thank you

.
Mar.09,2021

event delegate search keyword


<ul onclick="fun(event)">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script type="text/javascript">  
        function fun(e) {
            console.log(e)
        }
    
    </script>

https://www.cnblogs.com/liuga.

If the

event is bubbling, you only need to bind the event to their parent element, .container, and use ev.target to check which webview object triggered it.


Thank you for your answers. First of all, the console-message event is different from the click,mouseover event. It cannot bubble, nor can it be triggered manually. It is just an event that actively returns a string. Here I just use a very irregular solution, that is, directly for loop through the js method

.
const webview = document.querySelectorAll('webview')

    for(let i=0;i<webview.length;iPP){
        webview[i].addEventListener('console-message', e => {
            console.log(e.message);
            if(e.message.indexOf('')!==-1){
                alert('')
            }
        });
    }

although I know that this is very irregular, there is no better way at present

Menu