gpt4 book ai didi

jquery - 像 jQuery 一样处理 Angular 4 中 html 元素的点击?

转载 作者:行者123 更新时间:2023-12-01 08:42:39 24 4
gpt4 key购买 nike

在 jQuery 中,我们可以处理元素上的点击,而无需在 View 中写入任何内容:

$("#tableId thead tr th").on("click", function() {
console.log('click on TH');
});

是否可以在 Angular 4 中做同样的事情?

最佳答案

您可以通过 HostListner (MouseDown) 事件来实现它,当您的鼠标按下事件被触发时,它会调用 listner 事件,您必须在其中找到 taget 元素,如下所示:

您可以根据您的要求通过Class、ID、Tag获取所需的元素

即(event.target.className=="xyz")

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

constructor(private el: ElementRef) {
}

ngAfterViewInit()
{
this.RegisterMouseDown();
}

RegisterMouseDown() {
this.el.nativeElement.removeEventListener("mousedown", this.OnMouseDown.bind(this));
this.el.nativeElement.addEventListener("mousedown", this.OnMouseDown.bind(this));
}

OnMouseDown(event:any) {
if (event.target != null && event.target=="th") {
//user has clicked on th
}
else if (event.target != null && event.target=="img") {
//user has clicked on img
}
}

关于jquery - 像 jQuery 一样处理 Angular 4 中 html 元素的点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com