[英]Simple JavaScript Function Doesn't Work With No Errors
我是 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;
}
如果要打印輸入字段的值,可以使用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;
}
如果您希望它在頁面中可見,請在 HTML 中創建一個 div 並為其設置一個 id。 之后在 JS 中獲取變量中的值
var myId=document.getElementById("myid").value;
並將其設置在新的 div id 中。
document.getElementById("printId").innerHTML="myId";
你不會對這個值做任何事情,你只是取回它然后扔掉它。 嘗試
function myfunc() {
alert(document.getElementById("myid").value);
}
這是一個簡單的例子,這個函數不做任何事情。
您的代碼在獲取具有 id myid
的輸入字段的值方面是正確的。
但是在那之后你什么都不用做,如果你想看到它,你可以對值執行console.log()
,或者你可以將它分配給一個變量以便稍后在const inputValue = document.getElementById("myid").value;
上使用它const inputValue = document.getElementById("myid").value;
行document.getElementById("myid").value;
只是簡單地檢索該值,並且不對它做任何事情,只是將其扔掉,這就是為什么您看不到任何錯誤或反饋的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.