javascript - 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);
});
}
解决方案
你真的不需要这么详细,自己写。
其他人已经解决了这个问题,比如 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
}
}
推荐阅读
- javascript - vanilla js:SetInterval 和进度条
- html - A-frame:从场景实体调用的 html 对象
- spring-boot - 将 Spring Boot Web 应用程序中的 Spring Batch Admin 与另一个 JPA 持久性集成
- android - 如何以编程方式将固定大小设置为 TextView?
- python - Selenium/BeautifulSoup - Python - 循环多个页面
- import - 无法使用 CrawlerProcess 导入模块
- c# - 带有编码文本的自动热键
- python - 错误检查/处理 Web API 调用中的缺失值
- r - 在R中编写一个函数以按时间迭代地子集数据帧
- c++ - 使用 lambda 表达式和 std::function 时没有匹配的函数调用错误。