繁体   English   中英

访问HTMLCollection中的某些元素

[英]accessing certain element in HTMLCollection

我正在尝试在有角度的组件中使用document.getElementsByClassName ,但有时会得到意外的值。 document.getElementsByClassName有时会给出一个值(HTML元素),而其他时候是undefined

我在ngOnInit有这段代码

window.addEventListener('load', function (){
      let tabcontent = document.getElementsByClassName('tab');
      console.log(tabcontent[0]); // <----- 
    })

我在视图模板中有这个

<div id='parent_div_2'>
    <div *ngFor="let collection of collections; let i=index">
      <!--targeted element -->
      <div class="tab tab{{i}}" *ngIf="collection != null">
        <table class="table table-borderless">
          <tbody>
            <tr *ngFor="let each of collection.collApps; let i = index">
              <td>
                <img *ngIf="imageLoaded && this.imageToShow[i]" [src]="this.imageToShow[i]" 
                style="width:30%;" alt="Place image title">
              </td>
              <td> <h4>{{each.name}}</h4></td>
              <td> <form #form action="http://{{each.link}}"> 
                <input type="submit" value="Launch" (click)="form.submit()"/> 
              </form> </td>
            </tr>
          </tbody>  
        </table>
      </div>
    </div>
  </div>

有时console.log输出undefined而其他时候则提供一些HTML元素。 为什么document.getElementsByClassName有时给出undefined值的任何解释!

我不确定,但是可能是因为页面正在加载,并且您尝试访问的元素和元素仍未定义。 尝试使用这个...

window.addEventListener('DOMContentLoaded', (event) => {
    // do something
});

如果您使用的是角度,则应该以角度方式进行操作。 Angular有一个init事件,您可以调用:

<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};

看到这篇文章: 如何在页面加载时执行AngularJS控制器功能?

暂无
暂无

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

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