简体   繁体   English

如何在innerHTML中调用函数?

[英]How to call a function within innerHTML?

This is InnerHTML String 这是InnerHTML字符串
I'm calling a function within innerHTML but it is not considered as a function call Instead it simply print the code as it is if I use script tag. 我在innerHTML中调用一个函数,但是它不被视为函数调用,而是使用脚本标记直接按原样打印代码。

addCard()
  {
    if(this.cardItem.length == 0)
    {
      this.dataOrder = 0;
      this.temp = "<html><div class='col-md-4' id='replicateCard'><div class='card custom-card'><img class='card-img-top card-image' src='../../assets/images/user.png' alt='Card image cap'><a class='close' onclick='showAlert()'>×</a><div class='card-body card-body-custom'><br><p class='card-title'>"+this.dataTitle+"</p><p class='card-text'>"+this.dataDesc+"</p><p class='card-text'>"+this.dataDesc+"</p><p class='card-text'>"+this.dataOrder+"</p></div></div></div></html>";
      this.cardItem.splice(this.dataOrder, 0, this.temp);
    }
}

This is my function to call: 这是我要调用的函数:

 showAlert()
  {
    alert("I'm working");
  }

Although I would not recommend doing this way. 尽管我不建议这样做。 For your case you'll need to make sure second function is in the global scope. 对于您的情况,您需要确保第二个功能在全局范围内。

If not you can simply write it as 如果没有,你可以简单地写成

window.showAlert = function(){ alert("your message") }

Or you can bind the events dynamically to the new dom elements 或者您可以将事件动态绑定到新的dom元素

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

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