首页 > 解决方案 > EventListener 不触发

问题描述

我将我的 ionic3 更新为 ionic4 并且超链接不再起作用。所以我尝试为他们设置一个新的 ClickEvent。不幸的是,点击事件不起作用。即使我点击某个链接,我的活动内容也永远不会到达。我不明白为什么它不起作用。

ngAfterViewChecked() {
	if (!this._element) return;
	let arrUrls = this._element.nativeElement.querySelectorAll('a');
	console.log("arrUrls.length:", arrUrls.length); // Reached and correct
	console.log("arrUrls:", arrUrls); // Reached and correct
	this.setEventListener(arrUrls);
}


private setEventListener(arrUrls)
{
	arrUrls.forEach((objUrl) =>
	{
		console.log('5412212112121212'); // Reached
		console.log(objUrl); // Reached and correct
		// Listen for a click event on each hyperlink found
		objUrl.addEventListener('click', (event) =>
		{
			//NOT REACHED
		
			event.preventDefault();
			alert('7213983728912798312231'); // Isn't reached
			//this._link = event.target.href;
		}, false);
	});
}

标签: javascriptangularionic-frameworkionic4

解决方案


你真的不需要这么详细,自己写。

其他人已经解决了这个问题,比如 LinkifyJS 项目。

它有一个角度兼容的包装器:

其中,一旦您完成了标准设置过程,您就可以将其用作管道:

<span [innerHTML]="'Linkify the following URL: https://github.com/anthonynahas/ngx-linkifyjs and share it <3' | linkify"></span>

或作为服务:

import {NgxLinkifyjsService, Link, LinkType, NgxLinkifyOptions} from 'ngx-linkifyjs';

constructor(public linkifyService: NgxLinkifyjsService) {

  const options: NgxLinkifyOptions =
     {
      className: 'linkifiedYES',
      target : {
          url : '_self'
        }
      };

  this.linkifyService.linkify('For help with GitHub.com, please email support@github.com');
  // result 1 --> see below

  this.linkifyService.linkify('For help with GitHub.com, please email support@github.com', options);
    // result 2 --> see below
 } 
}

推荐阅读