[英]How can I output javascript with “onclick” into a textfield?
我寫了一個JavaScript程序來生成隨機密碼。 如何將結果輸出到文本字段(輸入標簽)?
var randomString = function(length) { var text = ""; var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890"; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } var rs = randomString(16); console.log(rs);
<section id="passgen"> <button type="button" id="pass-button" onclick="**???**">Generate Password</button> <br><br> <input type="text" name="output"> </section>
添加內聯click事件不是一個好主意,可以改用addEventListener
。
因此,在這里,我首先使用document.getElementById
選擇元素,並為其附加一個click
事件,然后,使用document.getElementsByName()
選擇輸出元素並打印隨機字符串。
另請注意,與document.getElementsByName()
一起使用的[0]
是因為如果代碼遇到名稱為output
多個元素,我們將選擇第一個,因為它會返回匹配元素的數組。 如果您可以在input
字段中添加一些id
,然后使用document.getElementById()
選擇特定的元素,那將是很好的選擇。
var randomString = function(length) { var text = ""; var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890"; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } document.getElementById('pass-button').addEventListener('click', function() { document.getElementsByName('output')[0].value = randomString(16); });
<section id="passgen"> <button type="button" id="pass-button">Generate Password</button> <br> <br> <input type="text" name="output"> </section>
您可以執行以下操作:
var randomString = function(length) {
var text = "";
var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
for(var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var rs = randomString(16);
console.log(rs);
document.getElementsByName('output')[0].value = rs;
非常簡單的document.getElementById("id_of_input_field").value = rs;
否則,您可以使用輸入框的名稱來定位document.getElementsByName('output')[0].value = rs;
var randomString = function(length) { var text = ""; var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890"; for(var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } var generatePassword = function(length) { document.getElementById('password').value = randomString(length); }
<section id="passgen"> <button type="button" id="pass-button" onclick="generatePassword(16)">Generate Password</button> <br><br> <input id='password' type="text" name="output"> </section>
給您的輸入一個ID,然后:
document.getElementById('yourInputID').value = rs;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.