[英]error TS2339: JavaScript to Typescript error
src / app / dashboard.component.ts(49,15)中的錯誤:錯誤TS2339:“元素”類型上不存在屬性“樣式”。 src / app / dashboard.component.ts(50,16):錯誤TS2339:屬性'textContent'在類型'EventTarget'上不存在。
這作為一個javascript函數,但上面是我嘗試在打字稿中使用它時得到的錯誤。 我已經嘗試更改var以允許和添加。 還有其他建議嗎? 謝謝。
dashboard.ts
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>
問題是target
被輸入為EventTarget
,而作為HTMLCollection
的image
元素被輸入為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
})
Yo也可能也想正確輸入hideDivs
:
// a function to hide all divs
const hideDivs = function (divs : HTMLCollection) {
for (var div of divs) {
(div as HTMLElement).style.display = 'none';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.