getElementById 仅在第一次有效

getElementById works only the first time

我正在使用 Ionic 2 并尝试在

上使用 getElementbyId
 <ion-content padding>    
   <ion-list id="list"></ion-list>    
 </ion-content>

以便我可以通过以下方式添加项目:

var listIon=document.getElementById("list");    
var li = document.createElement("ion-item");    
li.innerText=usern+": "+mensaje;    
var p = document.createElement("p");    
p.appendChild(li);    
listIon.appendChild(p);

它第一次工作得很好,但如果我退出页面并重新打开它,我会收到一条错误消息,提示

cannot read property appendChild on null

。我已经读过其他问题,他们说脚本不在底部。考虑到在 Ionic 中您根本没有将脚本放在 html 中,我不知道是什么原因造成的。

编辑

我已经上传了文件here主要问题是聊天详情,聊天详情是从聊天中打开的。

你到底想做什么?我认为您正在以 旧的 Jquery 方式思考 ,但是 Ionic 在 Angular2 之上工作,所以事情以不同的方式完成。

我假设您想将一个新项目附加到列表中,这可以通过使用 *ngFor 和一个数据数组来完成。或者,如果您想在特定条件下显示一条消息,您可以使用 *ngIf 来实现。 您应该尽量避免直接引用 DOM,而是更新组件代码来更改视图中显示的数据。

我创建这个 demo plunker 只是为了向您展示如何以 Angular2 方式 完成这些事情。请让我知道预期结果是什么,以便我可以相应地更新 plunker。

组件代码:

@Component({
  selector: 'page-home',
  templateUrl: 'app/home.page.html'
})
export class HomePage {

  private count: number;
  public users: Array<string>;

  public showMessage: boolean;
  public message: string;

  constructor() {
    this.count = 1;
    this.users = [];

    this.showMessage = false;
    this.message = 'This is a secret message!';
  }

  public addUser(): void {
    this.users.push(`User ${this.count++}`);
  }

  public toggleMessage(): void {
    this.showMessage = !this.showMessage;
  }

}

查看代码:

<ion-header>
  <ion-navbar>
    <ion-title>HomePage</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Users</h2>
  <p *ngIf="showMessage">{{ message }}</p>
  <ion-list *ngFor="let user of users">
    <ion-item>
      <p>{{ user }}</p>
    </ion-item>
  </ion-list>
  <button ion-button (click)="addUser()">Add a user</button>
  <button ion-button (click)="toggleMessage()">Togle message</button>

</ion-content>