当前位置: 代码迷 >> JavaScript >> 如何检查单选按钮选择值以匹配数组项
  详细解决方案

如何检查单选按钮选择值以匹配数组项

热度:76   发布时间:2023-06-05 10:19:12.0

我正在制作自己的lorem ipsum生成器,并尝试将单选输入值与数组值匹配,以便当它为true ,它将基于数组值生成文本。

例如,由于其中一个收音机具有value="harry"属性,并且generator.js文件中的characters arraycharacters 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;
        }
      }
    })
  }

但是我无法运行它,因为未定义文档。 我知道上面的代码块是一团糟,但我不知道如何使其工作。

我认为问题出在:

if(selection === characters[i])

'selection' is a string while 'characters[i]'不是。请使用如下字符对象:

characters ={'harry':harray, 'ron':ron}

并与字符键比较选择

if(characters[selection]){}

调试代码很难。.这是另一个建议:-使用document.getElementByClass而不是document.getElementsByName

  相关解决方案