繁体   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