错误TS2339:JavaScript到打字稿错误
作者:互联网
ERROR in src/app/dashboard.component.ts(49,15): error TS2339: Property
‘style’ does not exist on type ‘Element’.
src/app/dashboard.component.ts(50,16): error TS2339: Property
‘textContent’ does not exist on type ‘EventTarget’.
这可以用作javascript函数,但是以上是我在打字稿中尝试使用此错误.我尝试将var更改为let和add.还有其他建议吗?谢谢.
仪表板
var w = document.getElementById('wrapper');
var button = document.getElementById('randomize');
var image = w.children; // inner elements, your quotes divs
// a function to hide all divs
var hideDivs = function(divs) {
for (var div of divs) {
div.style.display = 'none';
}
}
hideDivs(image); // hide all initially
// on click
button.addEventListener('click', function(event) {
var rnd = Math.floor(Math.random() * image.length); // get random index
hideDivs(image); // hide all quotes
image[rnd].style.display = 'block'; // show random quote
event.target.textContent = 'Click one more time!'; // set button text. event.target is the button you've clicked
})
dashboard.html
<div id="wrapper">
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
</div>
<button id='randomize'>Next</button>
解决方法:
问题在于目标键入为EventTarget,而图像元素(即HTMLCollection)键入为Element.您要访问的两个属性都在HTMLElement上定义.您可以做的最简单的事情是使用类型断言来告诉编译器,就您而言,这两个实际上都是HTMLElement
// on click
button.addEventListener('click', function (event) {
var rnd = Math.floor(Math.random() * image.length); // get random index
hideDivs(image); // hide all quotes
(image[rnd] as HTMLElement).style.display = 'block'; // show random quote
(event.target as HTMLElement).textContent = 'Click one more time!'; // set button tqext. event.target is the button you've clicked
})
您可能还希望正确键入hideDivs:
// a function to hide all divs
const hideDivs = function (divs : HTMLCollection) {
for (var div of divs) {
(div as HTMLElement).style.display = 'none';
}
}
标签:angular,typescript,syntax-error,javascript 来源: https://codeday.me/bug/20191109/2011993.html