gpt4 book ai didi

javascript - 使用 .html() 清除以前的随机字符串不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:09 25 4
gpt4 key购买 nike

我正在编写一个简短的函数,它附加一个长度等于给定单词的随机字符串。例如,如果您输入单词“hello”,它将返回一个长度为 5 个字母的随机字符串。

这部分按预期工作。但是,我正在使用 $('output').html(""); 来覆盖最后一个随机字符串。我之前将它用于其他功能并且它按预期工作但它不在这里。我试过在函数周围移动它,看看它是否与函数的顺序有关,但它并没有删除之前的随机字符串。

我做错了什么?

Fiddle here

HTML:

<input type="text" id="input">
<button id="button">Click Me</button>
<div id="output"></div>

JavaScript:

var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function () {
$('#button').on('click', function () {

var value = ($('#input').val());
for (i = 0; i < value.length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
};
$('#input').val("");
$('#output').html("");
$('#output').html(text);
});
});

最佳答案

问题不在于 .html() 部分。问题是您的 var text 永远不会被重置。

供引用 - http://jsfiddle.net/oo5eLbpu/2/

更新后的答案如下

var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function() {
$('#button').on('click', function() {
var text = ""; // moved the variable inside the click handler
var value = ($('#input').val());
for (i = 0; i < value.length; i++) {
text += possible.charAt(Math.floor(Math.random() *
possible.length));
};
$('#input').val("");
$('#output').html("");
$('#output').html(text);
});
});

此外,您可以从代码中删除以下行

$('#output').html("");

因为它下面的行设置了元素的内容。

供引用 - http://jsfiddle.net/oo5eLbpu/4/

文档 - http://api.jquery.com/html/

关于javascript - 使用 .html() 清除以前的随机字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440147/

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