【问题标题】:How to find and add css class to one of div's children?如何查找css类并将其添加到div的孩子之一?
【发布时间】:2016-08-12 17:10:37
【问题描述】:
<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

<div class="post-content-container">
  <div class="post-content">
    Some very long text
  </div>
  <button (click)="showMore($event)">Show more</button>
</div>

单击按钮后,我想向post-content 添加一个类。嗯,首先我需要找到一个父母,对吧?然后,我想找到它的一个孩子并添加到它的自定义 css 类。

showMore(event: any) {
  let parent = event.target.parentNode; <-- post-content-container
  //now, how to get into parent's child (I mean post-content) and add to it some custom css class?
}

【问题讨论】:

    标签: events angular parent target


    【解决方案1】:

    您使用的是 Angular2 对吗?不需要像在 jQuery 中那样做任何自定义 JavaScript。以下是如何通过切换组件中的“showMyClass”值来添加类“myClass”,其中“showMyClass”属性是一个布尔值。或者使“showMyClass”成为一个布尔数组。这是一个完整的工作示例:

    import { Component, NgModule } from '@angular/core'
    import { BrowserModule } from '@angular/platform-browser'
    import { FormsModule }   from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      template:`
        <div class="post-content-container">
            <div class="post-content" [ngClass]="{myClass: showMyClass[0]}">
            Some very long text 1
            {{showMyClass[0]}}
            </div>
            <button (click)="showMore(0, $event)">Show more</button>
        </div>
    
        <div class="post-content-container">
            <div class="post-content" [ngClass]="{myClass: showMyClass[1]}">
            Some very long text 2
            {{showMyClass[1]}}
            </div>
            <button (click)="showMore(1, $event)">Show more</button>
        </div>
      `
    })
    export class App {
        public showMyClass: Array<boolean>;
    
        constructor(){
          this.showMyClass = [];
        }
    
        showMore(index, event: any) {
          this.showMyClass[index] = !this.showMyClass[index];
        }
     }
    
    
    @NgModule({
      imports: [ BrowserModule, FormsModule ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}
    

    【讨论】:

    • 好吧,也许我的帖子不清楚。可能有几个带有后内容 div 的后内容容器,我不想将该类添加到所有这些容器中。我只想在单击按钮的位置添加该类。
    • 我已经根据您更新的要求更新了我的答案 :-) 它使用“showMyClass”的布尔数组而不是单个属性。不是最好的实现,但它有效,你明白了。
    • 谢谢。你有我的好主意。我做了一些不同的事情,但也使用了索引。
    猜你喜欢
    • 2013-07-22
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2016-11-30
    • 2022-09-29
    • 1970-01-01
    • 2015-01-07
    • 2020-10-23
    相关资源
    最近更新 更多