问题描述
我正在制作自己的lorem ipsum生成器,并尝试将单选输入值与数组值匹配,以便当它为true
,它将基于数组值生成文本。
例如,由于其中一个收音机具有value="harry"
属性,并且generator.js文件中的characters array
在characters array
具有harry
变量。
它将从harry
文件生成文本。
到目前为止我的代码
// index.html
<form name="form" action="/" method="POST">
<div id="charType">
<label class="btn btn-warning char harry">
<input name="charType" type="radio" value="harry">Harry
</label>
<label class="btn btn-warning char ron">
<input name="charType" type="radio" value="ron">Ron
</label>
</div>
<input type="number" class="paragraph-number" name="numberOfParagraphs">
<input type="submit" value="Generate" class="generate-button">
</form>
<div class="generated-text">
<div class="placeholder-div"></div>
</div>
和我的generator.js
const harry = require("./harryText");
const ron = require("./ronText");
const loremIpsum = new GenerateNewText();
function GenerateNewText(){
characters = [
harry,
ron
]
}
这是有效的代码,但没有合并无线电选择功能,并且需要我必须对数组中的哪个变量进行硬编码才能访问。
GenerateNewText.prototype.getRandomSentence = function() {
let randomSentence = harry[Math.floor(Math.random() * harry.length)]
return randomSentence;
}
显然,我不想对harry
进行硬编码,而我想让randomSentence
根据所选的单选输入生成文本。
因此,我尝试将代码修改为其他形式
GenerateNewText.prototype.getRandomSentence = function() {
document.getElementsByName("charType").is("checked", function() {
var selection = this.val();
while(character < characters.length) {
if(selection === characters[i]) {
let randomSentence = [Math.floor(Math.random() * harry.length)]
return randomSentence;
}
}
})
}
但是我无法运行它,因为未定义文档。 我知道上面的代码块是一团糟,但我不知道如何使其工作。
1楼
Lomash Bhattarai
0
2019-02-21 06:12:01
我认为问题出在:
if(selection === characters[i])
'selection' is a string while 'characters[i]'
不是。请使用如下字符对象:
characters ={'harry':harray, 'ron':ron}
并与字符键比较选择
if(characters[selection]){}
调试代码很难。.这是另一个建议:-使用document.getElementByClass
而不是document.getElementsByName