如何查找和添加css类给div的一个孩子?

时间:2016-08-12 17:10:38

标签: events angular parent target

<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?
}

1 个答案:

答案 0 :(得分: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 {}