gpt4 book ai didi

javascript - 在 Angular 2 中渲染模板后运行 jQuery 代码

转载 作者:行者123 更新时间:2023-11-30 12:03:46 25 4
gpt4 key购买 nike

我有组件:

@Component({
selector: 'fx-app',
templateUrl: 'app/modules/main/page.html',
directives: [RouterOutlet,RouterLink,ROUTER_DIRECTIVES],
providers: [
ROUTER_PROVIDERS,
HTTP_PROVIDERS
]
})

export class MainComponent {
constructor(){
var menu = new MainMenu();
}
}

其模板 app/modules/main/page.htm:

<div id="menu">
<div class="logo"></div>
<div class="menuContainer">
<ul>
<li>
<a class="withNested closed">
<span class="word">Users</span>
</a>
</li>
<li>
<a [routerLink]="['Products']">
<span class="word">Products</span>
</a>
</li>
</ul>
</div>
</div>

<div id="content">
<router-outlet></router-outlet>
</div>

<div id="footer"></div>

MainMenu 如下所示:

export class MainMenu{

public menu = null;
public allLinks = null;

constructor(){
this.menu = $('#menu');
this.allLinks = $('#menu').find('a');
this.menu.find('ul a').click(this.setItem);
console.log('init MainMenu');
}

public setItem (){
this.allLinks.removeClass('active');
$(this).addClass('active');
if($(this).hasClass('withNested')){
if($(this).hasClass('opened')){
$(this).removeClass('opened');
$(this).addClass('closed');
$(this).next('ul').slideUp();
}else{
$(this).removeClass('closed');
$(this).addClass('opened');
$(this).next('ul').slideDown();
}
}
}

}

MainMenu 的代码不起作用,因为它在显示的模板 app/modules/main/page.htm 之前起作用。如何使 MainMenu 类的 jQuery 代码开始正常工作?

最佳答案

我认为您需要使用 ngOnInit(),因为它会在 dom 准备就绪后立即触发:

import {OnInit} from 'angular2/core';

export class MainMenu implements OnInit {

public menu = null;
public allLinks = null;

constructor(){

}

ngOnInit() {
this.menu = $('#menu');
this.allLinks = $('#menu').find('a');
this.menu.find('ul a').click(this.setItem.bind(this));
console.log('init MainMenu');
}

public setItem (e){
this.allLinks.removeClass('active');
$(e.currentTarget).addClass('active');
if($(e.currentTarget).hasClass('withNested')){
if($(e.currentTarget).hasClass('opened')){
$(e.currentTarget).removeClass('opened');
$(e.currentTarget).addClass('closed');
$(e.currentTarget).next('ul').slideUp();
}else{
$(e.currentTarget).removeClass('closed');
$(e.currentTarget).addClass('opened');
$(e.currentTarget).next('ul').slideDown();
}
}
}

}

关于javascript - 在 Angular 2 中渲染模板后运行 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com