属性src在jQuery类型上不存在

时间:2018-09-11 08:27:18

标签: angular typescript ionic-framework ionic2 ionic3

我正在尝试使用event.target更改图像的src。

在普通的html中,下面的js代码有效:

event.target.src = 'https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png';

但是在typescript中,它给出了错误。正如论坛上所建议的那样,我正在尝试使用以下代码在打字稿中实现,但遇到了另一个错误。

我该如何实现?下面是我的代码:

Home.ts

export class EditsectionPage {
  element: HTMLImageElement; /* Defining element for changing src */
...//more code here

// when I right click on image, context menu opens with a button, on clicking that button below code is fired

event.target.element.src = 'https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png';

即将到来的错误是:

  

[ts]属性“ element”在类型“ Element”上不存在。

如何解决此错误?

2 个答案:

答案 0 :(得分:2)

this.modalController.dismiss(); (类型为target)的event属性键入为Event。如果您知道目标是EventTarget,最简单的解决方案是在HTMLImageElement

上使用类型断言
targert

答案 1 :(得分:0)

您的事件是一个EventTarget。仅在您100%确信它将是HTMLImageElement时,才需要将目标强制转换为所需的类型。此外,event.target是您的元素,无需键入event.target.element。

产生的解决方案

export class EditsectionPage {
  element: HTMLImageElement; /* Defining element for changing src */

  //more code here

  /* when i right click on image, context menu opens with a button, on clicking that 
  button below code is fired */

  (event.target as HTMLImageElement).src = 'https://cdn.iconscout.com/icon/free/png-256/car-location- 
  find-navigate-gps-location-29571.png';

  //more code here
}