簡體   English   中英

click事件未在動態生成的元素上觸發

[英]click event is not firing on dynamically generated elements

從中動態添加到DOM的 HTML代碼。

  <ul>    
        <li>        
            <button (click)="Onclick(abc)" class="btn btn-sm btn-danger  click_for_save pull-right" type="button">
            <i class="fa fa-close"></i> Save </button>
        </li>                   
    </ul>

在HTML代碼中,這里有一個帶有參數的click事件。 (click)="Onclick(abc)"

現在,我動態添加它。 因此,點擊事件不起作用。

我為此進行了大量搜索,但無法找到解決方案。 我的打字稿代碼如下。

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

 // Below code I have added just after the dynamically added code.

  this.elementRef.nativeElement.querySelector('.click_for_save')
                                .addEventListener('click', this.click_for_save.bind(this)); 

Onclick(abc) {
  console.log(abc);
}

我收到此錯誤。

ERROR TypeError: Cannot read property 'addEventListener' of null

但是點擊事件沒有觸發。 我什SetTimeOut()嘗試了SetTimeOut()函數,間隔為3秒。

編輯:-

我正在檢查

let query_selector_value =  this.elementRef.nativeElement.querySelector('.click_for_save');
if(query_selector_value){
  query_selector_value.addEventListener('click', this.click_for_save.bind(this));
}

我正在獲取query_selector_value - null

嘗試使用此行,還要檢查以確保此類中只有一個元素:

this.elementRef.nativeElement.querySelector("[class='click_for_save']")
                                .addEventListener('click', this.click_for_save.bind(this));

還可以嘗試這樣做以查看是否存在多個具有相同類的元素:

var button = document.querySelector("[class='click_for_save']");
console.log(button);

看看是否有任何元素。

更新:

試試這個

$("body").on("click", ".click_for_save", function(){
  //do something
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM