为什么 Event.target 不是 Typescript 中的元素? [英] Why is Event.target not Element in Typescript?

查看:31
本文介绍了为什么 Event.target 不是 Typescript 中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想用我的 KeyboardEvent

var tag = evt.target.tagName.toLowerCase();

虽然 Event.targetEventTarget 类型,但它不继承自 Element.所以我必须像这样投射它:

var tag = (evt.target).tagName.toLowerCase();

这可能是由于某些浏览器不符合标准,对吗?TypeScript 中与浏览器无关的正确实现是什么?

附言我正在使用 jQuery 来捕获 KeyboardEvent.

解决方案

它不继承自 Element 因为并非所有事件目标都是元素.

来自 MDN:

<块引用>

元素、文档和窗口是最常见的事件目标,但其他对象也可以是事件目标,例如 XMLHttpRequest、AudioNode、AudioContext 等.

即使是您尝试使用的 KeyboardEvent 也可能发生在 DOM 元素或 window 对象上(理论上也发生在其他事物上),因此对于 没有意义>evt.target 被定义为 Element.

如果它是 DOM 元素上的事件,那么我会说您可以放心地假设 evt.target.是一个 Element.我不认为这是跨浏览器行为的问题.仅仅是 EventTarget 是一个比 Element 更抽象的接口.

进一步阅读:https://typescript.codeplex.com/discussions/432211

I simply want to do this with my KeyboardEvent

var tag = evt.target.tagName.toLowerCase();

While Event.target is of type EventTarget, it does not inherit from Element. So I have to cast it like this:

var tag = (<Element>evt.target).tagName.toLowerCase();

This is probably due to some browsers not following standards, right? What is the correct browser-agnostic implementation in TypeScript?

P.S. I am using jQuery to capture the KeyboardEvent.

解决方案

It doesn't inherit from Element because not all event targets are elements.

From MDN:

Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.

Even the KeyboardEvent you're trying to use can occur on a DOM element or on the window object (and theoretically on other things), so right there it wouldn't make sense for evt.target to be defined as an Element.

If it is an event on a DOM element, then I would say that you can safely assume evt.target. is an Element. I don't think this is an matter of cross-browser behavior. Merely that EventTarget is a more abstract interface than Element.

Further reading: https://typescript.codeplex.com/discussions/432211

这篇关于为什么 Event.target 不是 Typescript 中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆