gpt4 book ai didi

javascript - 存储在 Var 中并在 html 中调用的函数

转载 作者:行者123 更新时间:2023-12-05 00:30:54 25 4
gpt4 key购买 nike

想要创建随机代码,将其存储在变量中并在 html 中显示。

function GenerateButton() {
document.getElementById("btn1id").style.display = "none";
document.getElementById("Txt").style.display = "block";
document.getElementById("code").innerHTML = GFCode;
}

function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}

function codeFunc() {
document.write(randomString(4, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
document.write("-");
document.write(randomString(4, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
}
var GFCode = codeFunc;
<div class="btn0" id="btn1id" onclick="GenerateButton()">Generate</div>
<div class="Txt" id="Txt" style="display=none;"> The Code is: <span id="code"></span></div>

如果我在生成代码的 html 文档中执行 document.write,但我无法从 js 文档中获取它。

最佳答案

您的问题指出:“...创建随机代码,将其存储在变量中并以 html 显示。”
不要使用 document.write 。只需返回一个字符串,将其分配给一个变量,然后在您的 HTML 中插入该变量。为此,您需要执行 codeFunc() ,然后将返回的随机代码(字符串)分配给 GFCode :

function GenerateButton(){
document.getElementById("btn1id").style.display = "none";
document.getElementById("Txt").style.display = "block";
document.getElementById("code").innerHTML = GFCode;
}

function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}

function codeFunc(){
return ( // <-- return the code string
randomString(4, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
+ "-"
+ randomString(4, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
);
}
var GFCode = codeFunc(); // <-- execute codeFunc
<div class="btn0" id="btn1id" onclick="GenerateButton()">Generate</div>
<div class="Txt" id="Txt" style="display=none;"> The Code is: <span id="code"></span></div>


如果,正如您的标题所暗示的那样,您打算将函数存储在变量中,而不是函数产生的随机代码中,您可以:
...
document.getElementById("code").innerHTML = GFCode(); // <-- execute function
...
var GFCode = codeFunc; // <-- assign function to variable
无论哪种方式,都需要从函数返回随机代码,并且需要执行该函数。

关于javascript - 存储在 Var 中并在 html 中调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72595277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com