Vs code .value is not recognized by intellisense

空扰寡人 提交于 2020-04-11 08:33:07

问题


I am very new to javascript, but as I was working I was trying to figure out a way to get the text a user would input into an html input text box, but for some reason vs code does not recognize the intellisense required to do this. [my html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="first-input">
    <button id="submit-button">Submit</button>
    <script src="main.js" type="text/javascript"></script>
</body>
</html>

]1

[

let firstInput = document.getElementById('first-input');
let submitButton = document.getElementById('submit-button');

submitButton.onclick = function () {
    console.log(firstInput.value);
}

]2

In order to get the data inside an input text element, the code for that is .value, however when i start typing ".val-" the only recommendation VS code has is for .nodeValue.

no .value option, only .nodeValue

This means, in order to get what I want, I am using a command that the intellisense for vs code doesn't recognize. However, even though intellisense does not find it, the code still operates as intended.

code is functional

Is there something I need to install or do to get access to this information? I am concerned there are many other things it doesn't recognize and will make learning this language more difficult. Thanks in advance


回答1:


This is because getElementById() doesn't necessarily return an element with a .value property. For example, it could return a <div> element.

In order for the intellisense to know that you will have a .value property, you have to indicate with a JSDoc comment that the variable firstInput is going to be an <input> element. Like this:

/**
 * @type HTMLInputElement
 */
let firstInput = document.getElementById('first-input');
/**
 * @type HTMLButtonElement
 */
let submitButton = document.getElementById('submit-button');

submitButton.onclick = function () {
  console.log(firstInput.value);
}

Not to confuse you, but VSCode uses TypeScript to power its intellisense, even for JavaScript code.



来源:https://stackoverflow.com/questions/55271251/vs-code-value-is-not-recognized-by-intellisense

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!