简体   繁体   中英

Adding click event to dynamically generated html

I'm building an ionic app that lets users chat between each other.

In the event of a user sending a url as plain text, I have a function called urlify that replaces the text with html, and when a user clicks on the html for the url it should take them to that url.

The problem is, anchor elements don't open urls in Ionic, so I have to use window.open(url) ..

Here is my code:

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<span class="message-link">' + url + '</span>';
    })
  }
}

openLink(url) {
  window.open(url, '_system')
}

So when a user clicks the span it should open openURL but since I can't add (click)="openURL(url)" to the dynamically generated html, I'm not sure what to do..

Any ideas? Thank you!

This can help you, you can add anything dynamically on this way.

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        let newElement = document.createElement('span');
        newElement.innerHTML = url
        newElement.classList.add('message-link');
        newElement.onclick = function() {
            window.open(url, '_system')
        }
        return newElement
    });
  }
}

You can return this newElement or append it here, for example document.getElementById('someDivID').append(newElement) on this way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM