Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用typescript单击时删除画布元素_Javascript_Typescript - Fatal编程技术网

Javascript 使用typescript单击时删除画布元素

Javascript 使用typescript单击时删除画布元素,javascript,typescript,Javascript,Typescript,我是typescript新手,我正在尝试的是从div中删除canvas元素 <div class="chart"> <canvas id="nav-chart"></canvas> </div> 尝试此操作时,它会在以下行抛出错误:const elem:HTMLElement=document.getElementById('nav-chart') TS2322: Type 'HTMLElement | null' is not assi

我是typescript新手,我正在尝试的是从div中删除canvas元素

<div class="chart">
    <canvas id="nav-chart"></canvas>
</div>
尝试此操作时,它会在以下行抛出错误:const elem:HTMLElement=document.getElementById('nav-chart')

TS2322: Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
  Type 'null' is not assignable to type 'HTMLElement'.
const elem: HTMLElement | null = document.getElementById('nav-chart')
在这行
elem.parentElement.removeChild(elem)


我首先找到了解决方案,我们必须用
HTMLElement|null

TS2322: Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
  Type 'null' is not assignable to type 'HTMLElement'.
const elem: HTMLElement | null = document.getElementById('nav-chart')
而且在条件之内

if (elem) {
      elem.parentElement && elem.parentElement.removeChild(elem)
}