从[innerHTML]内容访问全局功能

时间:2018-10-21 02:14:03

标签: javascript angular typescript

在这个StackBlitz中,我有一个Angular组件,它用[innerHTML]显示内容。 HTML具有锚点,如果单击该锚点,它将跳到页面的另一行(该行应显示在页面顶部)。

问题是我无法从内部HTML访问javascript函数(我将其命名为goto),即使该函数似乎是全局的。

我得到的错误是:Uncaught ReferenceError: goto is not defined

如何进行这项工作?

function goto(id){
   var element = document.getElementById(id);
   element.scrollIntoView(true); 
}

@Pipe({name: 'safeHtml'})
export class Safe {
  constructor(private sanitizer: DomSanitizer){}
  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

@Component({
  selector: 'my-app',
  template: '<div [innerHTML]="content | safeHtml"></div>'
})
export class AppComponent  {

    content = `      
      <a href=javascript:goto('target')>
           Jump to 'Target' 
      </a>
      <br/><br/><br/><br/><br/><br/>
      <p id="target">This is 'Target'</p>
    `; 
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用内联Javascript。对该代码进行了少许更改以演示此here

AppComponent类如下:

export class AppComponent  {

    content = `      
      <a href="#" onClick="(
      function() {
        var element = document.getElementById('target');
        element.scrollIntoView(true); 
      }
    )()">
      Jump to 'Target'
    </a>

    <div id="mydiv" style="height: 250px; width:250px; overflow: auto; background: yellow;">
      <div id="target" style="margin: 500px; height: 500px; width:250px; background-color:green;">
        This is 'Target'
      </div>
    </div>   
    `; 
}

单击之前的用户界面:

enter image description here

点击后的用户界面:

enter image description here

相关问题