![](/img/trans.png)
[英]It's possible to grab javascript variable from an external HTML file with PHP
[英]how to grab an input in an html file and grab it from javascript file to
我在 html 中設置了以下內容
<input maxlength="1" type="number" min="1" max="4" id ="c0r0"></input>
這有一個文本框,我可以在其中輸入 select 一個 1 到 4 的數字,如果我 select 一個數字,我希望它在我的 js 文件中作為變量
我在我的 js 文件中試過這個:
var tt = document.getElementsByTagName("input")[0].value;
console.log(tt);
我需要它 tt var 等於輸入。 我需要添加一個按鈕來提交我的輸入嗎? 或者一旦我 select 1 到 4 我的 js 文件可以獲取值
我想指出這兩件事
<input type="number">
元素並不是真正用於“選擇”值的。 盡管您當然可以使用一些自動完成庫來幫助您。 <select>
元素可能是該任務更自然的選擇。const
:const tt=document.querySelector("input");
// the "variable" you require is then tt.value:
console.log(tt.value)
在“真實”應用程序中,您可能應該使用更具體的 CSS 選擇器,例如 class 或身份。
您可以嘗試更改:
<input maxlength="1" type="number" min="1" max="4" id ="c0r0"></input>
到:
<input maxlength="1" type="number" min="1" max="4" id="c0r0" />
以下是執行此操作的兩種簡單方法。
將更改事件偵聽器附加到輸入元素,即每次值更改時調用的 function。 然后使用事件的目標屬性來獲取值。 有關詳細信息,請閱讀此onchange 事件
使用getElementById
( 了解更多)獲取 html 元素引用,然后使用該元素訪問該值。
注意:使用getElementById
非常簡單,因為您可以獲得目標元素,而其他方法返回一個集合,您必須在集合中找到相關元素。
下面是上面推薦方法的一個小demo
function getValue(event) { // Method 1 var val = event.target.value console.log('first box:' + val); } function method2() { // Method 2 val = document.getElementById('c1r1').value; console.log('second box:' + val) }
<input maxlength="1" type="number" min="1" max="4" id="c0r0" onchange="getValue(event)" /> <input maxlength="1" type="number" min="1" max="4" id="c1r1" onchange="method2(event)" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.