简体   繁体   English

如何在inner.html中调用函数

[英]How to call function inside the inner.html

This is my normal function in JS file. 这是我在JS文件中的正常功能。 I need to closeHomeScreenPopup function which is defined inside the document.getElementById("addToHomeScreenPrompt").innerHTML . 我需要closeHomeScreenPopupdocument.getElementById("addToHomeScreenPrompt").innerHTML内部定义的closeHomeScreenPopup函数。 I have passed onclick as string as you can see. 如您所见,我已经将onclick作为字符串传递了。

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 但是在div onclick时出现错误

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

How can I call the closeHomeScreenPopup from inside inner.html 我怎样才能调用closeHomeScreenPopup从内inner.html

Everything in JS is bound to containing scope. JS中的所有内容都必须包含作用域。 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 closeHomeScreenPopup函数应全局定义

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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