简体   繁体   中英

How to call function inside the inner.html

This is my normal function in JS file. I need to closeHomeScreenPopup function which is defined inside the document.getElementById("addToHomeScreenPrompt").innerHTML . I have passed onclick as string as you can see.

export default function register() {
  // Checks if should display install popup notification:
  if (isIos() && !isInStandaloneMode()) {
    function closeHomeScreenPopup() {
      console.log("jkjilkjlkjlkjlkjlkjlk");
    }
    document.getElementById("addToHomeScreenPrompt").innerHTML =
      '<div onclick="closeHomeScreenPopup()"><span class="plush--sign">+</span><p>Install the webapp on your iPhone:tap <img style="width: 20px; margin: 0 4px;" alt="" src="img/share_icon.png"/> and then Add to homescreen.</p></div>';
  }
}

But I get error when do onclick on the div

Uncaught ReferenceError: closeHomeScreenPopup is not defined
    at HTMLDivElement.onclick (temperature-schedule?roomId=2:51)

How can I call the closeHomeScreenPopup from inside inner.html

Everything in JS is bound to containing scope. Therefore, if you define a function directly in the register functions, it will not be bound to window object.

closeHomeScreenPopup function should be defined globally

 window[closeHomeScreenPopup] = function() {
      console.log("jkjilkjlkjlkjlkjlkjlk");
    }

 function closeHomeScreenPopup() { console.log("jkjilkjlkjlkjlkjlkjlk"); } document.getElementById("addToHomeScreenPrompt").innerHTML = '<div onclick="closeHomeScreenPopup()"><span class="plush--sign">+</span><p>Install the webapp on your iPhone:tap <img style="width: 20px; margin: 0 4px;" alt="" src="img/share_icon.png"/> and then Add to homescreen.</p></div>'; 
 <div id="addToHomeScreenPrompt"></div> 

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