2016-08-12 47 views
1
<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类。如何查找和添加css类到一个div的孩子?

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

您正在使用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 {} 
+0

嗯,也许我的帖子不清楚。可以有几个后置内容容器和后置内容div,我不想将它们添加到所有这些类中。我想添加那个只有点击按钮的类。 – elzoy

+0

我已经更新了我的答案和更新的要求:-)它使用“showMyClass”而不是单个属性的布尔值数组。不是最好的实现,但它的工作原理,你明白了。 –

+0

谢谢。你有我很好的主意。我做了一些有点不同,但也与索引使用。 – elzoy