我对js很陌生,我的第一个也是最简单的函数没有错误。
其他js代码可以正常工作,但不是这样。
下面是代码:我希望它能简单地打印我在输入字段中所写的内容
HTML文件:
<html>
<head></head>
<body>
<input type="text" id="myid">
<button onclick="myfunc()">click</button>
<script src="javascript.js"></script>
</body>
</html>
javascript.js文件:
/*global document */
function myfunc() {
"use strict";
document.getElementById("myid").value;
}
发布于 2020-08-25 00:19:46
如果要打印输入字段的值,可以使用console.log()
将其内容打印到控制台。例如,将输入的值保存在变量中。然后,您可以在浏览器的控制台中记录此变量的值,或者将其用于其他目的。
function myfunc() {
"use strict";
var value = document.getElementById("myid").value;
console.log(value)
}
document.getElementById("myid").value
只获得了输入的值。但你什么都没做。
您还可以直接记录值,而不必先将其保存到变量中,请参见下面的示例。
function myfunc() {
"use strict";
console.log(document.getElementById("myid").value)
}
要在页面上显示该值,您可以创建一个空占位符,该占位符具有可以锁定的ID。然后将此占位符的textContent
设置为输入的值。参见下面的示例。
<html>
<head></head>
<body>
<input type="text" id="myid">
<button onclick="myfunc()">click</button>
<!-- This is the output placeholder -->
<p id="output"></p>
<script src="javascript.js"></script>
</body>
</html>
function myfunc() {
"use strict";
var value = document.getElementById("myid").value;
/* Select the output placeholder */
var outputElement = document.getElementById("output");
/* Set the input fields value as the text content */
outputElement.textContent = value;
}
发布于 2020-08-25 00:30:40
如果要在页面中显示该内容,请在HTML中创建一个div并为其设置一个id。之后,在JS中获取变量中的值。
var myId=document.getElementById("myid").value;
并将其设置在新的div id中。
document.getElementById("printId").innerHTML="myId";
发布于 2020-08-25 00:17:17
你不做任何有价值的事情,你只要把它拿回来扔掉就行了。试一试
function myfunc() {
alert(document.getElementById("myid").value);
}
https://stackoverflow.com/questions/63574691
复制相似问题