我在课堂上学到了如何创建一个能够生成输入单词的所有组合的函数。但是,如何使它不会出现窗口提示或警告弹出输入单词并在提示框中显示所有组合,我想在屏幕上显示结果。我将如何通过我已编写的代码来做到这一点?
这是我的完整代码:
<!DOCTYPE html>
<html>
<title>Combinations of a Word</title>
<body>
<script>
function combinations(str){
var substr = [];
for (var x = 0; x < str.length; x++)
{
for (var y = x + 1; y <= str.length; y++)
{
substr.push(str.substring(x,y));
}
}
return substr;
}
document.write(combinations(window.prompt("Please enter a word")));
</script>
</body>
</html>
答案 0 :(得分:0)
简单
<input type="text" id="word"/>
<div id="comb"></div>
的JavaScript
function combinations(str) {
var substr = [];
for (var x = 0; x < str.length; x++) {
for (var y = x + 1; y <= str.length; y++) {
substr.push(str.substring(x, y));
}
}
return substr;
}
var input = document.getElementById('word');
var out = document.getElementById('comb');
input.addEventListener('keyup', function(e){
out.innerHTML = combinations(this.value).join(',');
});
PS - 您的组合代码错误