【问题标题】:Traversing DOM to remove class using typescript使用打字稿遍历DOM以删除类
【发布时间】:2021-01-23 19:47:08
【问题描述】:

我在导航到表格中的元素方面需要帮助。 html 如下所示,

<table role="grid">
    <thead class="ui-table-thead">...</thead>
    <tbody class="ui-table-tbody" ng-reflect-columns="[object Object],[object Object" ng-reflect-template="[object Object]">...</tbody>
    <tr tabindex="0" class="ui-selectable-row ng-star-inserted ui-state-highlight" ng-reflect-data="[object Object]">...</tr>
</table>

这是我的导航代码:

if(this.table){
    console.log(this.table.tableViewChild.nativeElement);
    let element = this.table.tableViewChild.nativeElement.children;
    for(let key in element){
        if ((element[key].classList).contains('ui-table-tbody')) {
            (element[key].classList).remove('ui-state-highlight');
          }
    }
}

上面的代码没有帮助。我没有看到任何变化。有人可以让我知道如何删除foll。动态类'class=“ui-state-highlight”'。提前致谢。 请问有什么线索吗?

【问题讨论】:

  • .contains(...) 返回一个布尔值,而不是一个元素。
  • 问题是您正在检查一个包含 ui-table-tbody 类但不包含 ui-state-highlight 的元素,因此根据您提供的信息和代码 sn-ps 没有发生任何事情没有任何问题。或者您的 tbody 元素是否应该在某个时候包含 ui-state-highlight 类?
  • @Romuald 是的,没错。 tbody 没有“ui-state-highlight”。它是包含“ui-state-highlight”类的 tr 元素。那么我如何遍历到 tbody 然后 tr 并找到类?
  • 你为什么不简单地检查一下(element[key].classList).contains('ui-state-highlight')
  • @Romuald 我试过并得到了这个错误。错误类型错误:无法获取未定义或空引用的属性“包含”

标签: javascript html angular


【解决方案1】:

如果你使用@ViewChild来声明一个表:

@ViewChild 声明的元素仅在视图初始化后可用,这发生在 ngAfterViewInit

所以试着把你的函数放在ngAfterViewInit Angular Lifecycle Hook 中。

有关此主题的更多信息: Angular 2 @ViewChild returns undefined

【讨论】:

    【解决方案2】:

    另外,我将只使用类名搜索,但由于您使用的是 Angular,因此只在组件中搜索是合适的,而不是在整个 DOM 中搜索。

    检查这个问题/答案:

    Angular2 retrieve all elements with class name

    所以,我会尝试按照@Paritosh 的回答并这样做:

    1. 在构造函数中注入ElementRef:

      constructor(private renderer: Renderer, private elem: ElementRef){}

    然后

    1. 使用 ngAfterViewInit:

      ngAfterViewInit() {
      让元素 = this.elem.nativeElement.querySelectorAll('.ui-table-tbody');
      for(让元素的元素){
      elem.classList.remove('ui-state-highlight')
          }
      }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2021-08-26
      相关资源
      最近更新 更多