【问题标题】:accessing certain element in HTMLCollection访问 HTMLCollection 中的某个元素
【发布时间】:2019-11-23 12:36:39
【问题描述】:

我试图在一个角度组件中使用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 价值!!

【问题讨论】:

  • 你应该使用@ViewChildren并订阅QueryList.changes事件,如this answer和this other answer所示。
  • 这一行告诉我collection != null,只有collection 不为null 时该选项卡才可用。收藏总是固定的吗?我问是因为您的代码总是在加载时执行,如果在某些情况下该集合不存在,它将返回 undefined。
  • collection 始终不为空
  • @AZSH - 请展示你在@ViewChildren技术中使用的代码和HTML标记的stackblitz。
  • @ConnorsFan 我不再使用document.getElementsByClassName。相反,我使用了我以前不知道的@ViewChildren。

标签: javascript html angular typescript web-deployment


【解决方案1】:

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

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

【讨论】:

  • 但是包含document.getElementsByClassName的代码行应该在页面加载时运行!!
  • DOMContentLoaded 产生更差的结果。我一直收到undefined。
【解决方案2】:

如果你使用 Angular,你应该以 Angular 的方式做事。 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
};

看到这个帖子:How to execute AngularJS controller function on page load?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多