简体   繁体   English

我如何在我自己的在线测验中将这个 JS 代码重用于其他问题? 对象? 构架?

[英]How could I reuse this JS code for other questions in my own online quiz? Objects? Frameworks?

How to go about reusing my js code without just copying it and changing the names of variables?如何在不复制和更改变量名称的情况下重用我的 js 代码? I want to add more questions but reuse the same code?我想添加更多问题但重复使用相同的代码? This is a simple web test/quiz.这是一个简单的网络测试/测验。

CURRENT CODE CurrentUI当前代码CurrentUI

HTML HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DOM STUFF</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <h1 id="counter-display">Total:</h1>

    <div id="questionBox">
      <p id="question">Q1: What is My favorite Food?</p>
      <p>
        <input type="radio" name="answer" value="Chicken" /> Chicken
        <input type="radio" name="answer" value="Pork" /> Pork
        <input type="radio" name="answer" value="Seafood" /> Seafood
        <input type="radio" name="answer" value="Junkfood" /> Junfoods
        <input type="radio" name="answer" value="Vegetables" /> Vegetables
      </p>
      <p>
        <button id="Submit">Submit</button>
      </p>
    </div>

    <script src="dom.js"></script>
  </body>
</html>

JS JS

let Submit = document.getElementById('Submit');
let counterDisplayElem = document.getElementById('counter-display');
let question = document.getElementById('question');
let correctAns = 'Pork';
let total = '0';


//submit q1 on click, calling scoreQuestion 
Submit.addEventListener('click', () => {
    scoreQuestion();
});

//score q1
function scoreQuestion(params) {
    let answerArray = document.getElementsByName('answer');
    answerArray.forEach((answer) => {
        if (answer.checked) {
            if(answer.checked && answer.value ==correctAns){
                total++
                counterDisplayElem.innerHTML += total;
                Submit.style.display = 'none'; //hide submit on correct entry
            } else {
                alert("Incorrect");
                question.innerHTML += " Epic Fail";
            }
        }
    })
}

ATTEMPTED SOLUTION MY GOAL Solution UI尝试的解决方案我的目标解决方案用户界面

When I try to add more questions I must add more imports and variables as well.当我尝试添加更多问题时,我还必须添加更多导入和变量。 Is there an idea I am missing or is this just the way it is with web development?是否有我遗漏的想法,或者这只是网络开发的方式?


let question1 = document.getElementById('question1');
let question2 = document.getElementById('question2');
let question3 = document.getElementById('question3');
let Submit1 = document.getElementById('Submit1');
let Submit2 = document.getElementById('Submit2');
let Submit3 = document.getElementById('Submit3');


//submit q1 
Submit1.addEventListener('click', () => {
    scoreQuestion();
});
//score q1
function scoreQuestion1(params) {}



//submit q2
Submit2.addEventListener('click', () => {
    scoreQuestion3();
});
//score q2
function scoreQuestion2(params) {}



//submit q3 
Submit3.addEventListener('click', () => {
    scoreQuestion3();
});
//score q3
function scoreQuestion3(params) {}




HTML

 <div id="questionBox1">
      <p id="question1">Q1: What is My favorite Food?</p>
      <p>
        <input type="radio" name="answer1" value="Chicken" /> Chicken
        <input type="radio" name="answer1" value="Pork" /> Pork
        <input type="radio" name="answer1" value="Seafood" /> Seafood
        <input type="radio" name="answer1" value="Junkfood" /> Junfoods
        <input type="radio" name="answer1" value="Vegetables" /> Vegetables
      </p>
      <p>
        <button id="Submit1">Submit</button>
      </p>
    </div>

    <div id="questionBox2">
      <p id="question2">Q1: What is My favorite ETC?</p>
      <p>
        <input type="radio" name="answer2" value="Chicken" /> Chicken
        <input type="radio" name="answer2" value="Pork" /> Pork
        <input type="radio" name="answer2" value="Seafood" /> Seafood
        <input type="radio" name="answer2" value="Junkfood" /> Junfoods
        <input type="radio" name="answer2" value="Vegetables" /> Vegetables
      </p>
      <p>
        <button id="Submit2">Submit</button>
      </p>
    </div>

    <div id="questionBox3">
      <p id="question3">Q1: What is My favorite ETC?</p>
      <p>
        <input type="radio" name="answer3" value="Chicken" /> Chicken
        <input type="radio" name="answer3" value="Pork" /> Pork
        <input type="radio" name="answer3" value="Seafood" /> Seafood
        <input type="radio" name="answer3" value="Junkfood" /> Junfoods
        <input type="radio" name="answer3" value="Vegetables" /> Vegetables
      </p>
      <p>
        <button id="Submit3">Submit</button>
      </p>
    </div>

Just rewriting the code and changing the variable questionbox 1 2 and 3 and answer 1 2 and 3 and submit 1 2 and 3 feels wrong and disgusting and I am sure there is a simpler and easier way to do this.只是重写代码并更改变量问题框1 2 和 3 并回答1 2 和 3 并提交1 2 和 3 感觉错误和恶心,我相信有一种更简单、更容易的方法来做到这一点。 Makes me feel dirty lol.让我觉得很脏哈哈。

Any input is appreciated.任何输入表示赞赏。

B

Here's a simple use case for your function through a loop.这是您的函数通过循环的一个简单用例。 I put it in the click handler itself to make it easier to access the elements.我把它放在点击处理程序本身中,以便更容易地访问元素。 If you need this function separately, you will have to pass the elements through parameters.如果您单独需要此功能,则必须通过参数传递元素。

Here I changed the id to class , and added a data-set on the radio elements to mark the correct answers.在这里,我将id更改为class ,并在无线电元素上添加了一个数据集以标记正确答案。 If you need to hide them, you can add an array with responses in the sequence of HTML elements and notice the data-set for the correct[index] in js function.如果您需要隐藏它们,您可以在 HTML 元素序列中添加一个包含响应的数组,并注意 js 函数中正确 [index]数据集

 let counterDisplayElem = document.getElementById('counter-display'); let total = 0; const questionList = document.querySelectorAll('.questionBox'); questionList.forEach(function(item) { const btnSubmit = item.querySelector('.submit'); const question = item.querySelector('.question'); btnSubmit.addEventListener('click', function() { let answerArray = document.getElementsByName('answer'); answerArray.forEach((answer) => { if (answer.checked) { if(answer.checked && answer.dataset.correct === 'true'){ total++; counterDisplayElem.innerHTML = 'Total: ' + total; btnSubmit.style.display = 'none'; } else { alert("Incorrect"); question.innerHTML += " Epic Fail"; } } }); }); });
 <h1 id="counter-display">Total:</h1> <div class="questionBox"> <p class="question">Q1: What is My favorite Food?</p> <p> <input type="radio" name="answer" value="Chicken" /> Chicken <input type="radio" name="answer" value="Pork" data-correct="true" /> Pork <input type="radio" name="answer" value="Seafood" /> Seafood <input type="radio" name="answer" value="Junkfood" /> Junfoods <input type="radio" name="answer" value="Vegetables" /> Vegetables </p> <p> <button class="submit">Submit</button> </p> </div> <div class="questionBox"> <p class="question">Q2: What is My favorite Food?</p> <p> <input type="radio" name="answer" value="Chicken" data-correct="true" /> Chicken <input type="radio" name="answer" value="Pork" /> Pork <input type="radio" name="answer" value="Seafood" /> Seafood <input type="radio" name="answer" value="Junkfood" /> Junfoods <input type="radio" name="answer" value="Vegetables" /> Vegetables </p> <p> <button class="submit">Submit</button> </p> </div> <div class="questionBox"> <p class="question">Q3: What is My favorite Food?</p> <p> <input type="radio" name="answer" value="Chicken" /> Chicken <input type="radio" name="answer" value="Pork" /> Pork <input type="radio" name="answer" value="Seafood" /> Seafood <input type="radio" name="answer" value="Junkfood" /> Junfoods <input type="radio" name="answer" value="Vegetables" data-correct="true" /> Vegetables </p> <p> <button class="submit">Submit</button> </p> </div>

Yes copy-paste-edit is wrong.是的,复制粘贴编辑是错误的。 This code does not scale.此代码不缩放。 Ideally the questions' html is created from an array of question objects using Javascript.理想情况下,问题的 html 是使用 Javascript 从一系列问题对象创建的。 Designing a "Question" object and an array will drastically simplify passing data to html construction, event handling, and keeping an up to date set of questions.设计“问题”对象和数组将大大简化将数据传递到 html 构造、事件处理和保持最新问题集的过程。

  • All question html is the same so write a single function to create the html, passing in a question object.所有问题 html 都是相同的,因此编写一个函数来创建 html,并传入一个问题对象。

  • All submit buttons are likewise similar so a single function for building that also.所有提交按钮同样相似,因此也有一个单一的功能来构建它。

  • To add a question you should be able to just add it to the questions array.要添加问题,您应该能够将其添加到问题数组中。 Same for deleting or changing a question.删除或更改问题也是如此。

  • Use only one event handler.仅使用一个事件处理程序。 As all questions are handled the same and they all add to the same total.由于所有问题的处理方式相同,并且它们都加到相同的总数中。


Specific frameworks are not required to do this.不需要特定的框架来做到这一点。


  1. Create an array of Question objects with needed properties: "id", "question", "name", "correctAnswer".创建具有所需属性的 Question 对象数组:“id”、“question”、“name”、“correctAnswer”。 Maybe "yourAnswer" also.也许“你的答案”也是。

  2. event handler function;事件处理函数; pass all the particulars of that question as arguments to the event handler call.将该问题的所有细节作为参数传递给事件处理程序调用。 Passing all this as a question object will probably make referencing easier.将所有这些作为问题对象传递可能会使引用更容易。

  3. Don't call the button "submit" because "submit" has a particular, well known, idiomatic meaning in html/javascript data entry.不要将按钮称为“提交”,因为“提交”在 html/javascript 数据条目中具有特定的、众所周知的、惯用的含义。 It means to pass/process the entire form and there is a special built-in button type for this.这意味着传递/处理整个表单,并且有一个特殊的内置按钮类型。

Use event.target to detect wich element is selected then you click on input /or use JQuery :使用event.target检测选择的元素,然后单击输入/或使用 JQuery :

const Submit = $('#Submit');
const counterDisplayElem  = $('#counter-display');
Submit.change(function() {
if(this.checked && this.value == correctAns) {
    scoreQuestion(this.value)
} else {
            alert("Incorrect");
            question.innerHTML += " Epic Fail";
        }
});

function scoreQuestion(params) {
            total++
            alert('Correct->'+params);
            counterDisplayElem.innerHTML += total;
            Submit.style.display = 'none';
}

You need something like this.你需要这样的东西。 This is far from ideal code and its more like example how you might achieve reusability and avoid duplication, but after you grasp a bit of idea, you can deep dive in details and possibilities.这远非理想的代码,它更像是如何实现可重用性和避免重复的示例,但是在掌握了一些想法之后,您可以深入了解细节和可能性。 https://jsfiddle.net/8rhjL4gw/59/ https://jsfiddle.net/8rhjL4gw/59/

 <div id="questions"> </div> <script> const list = document.getElementById('questions'); const data =[{ question: 'My favourite food is?', answers: ['chicken', 'pork'] }, { question: 'My favourite dring is?', answers: ['water', 'juice', 'vodka'] }]; data.forEach((x,index)=> { const question = document.createElement('p'); question.innerText = x.question; list.appendChild(question); x.answers.forEach(answer => { const radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', 'answer'+index); radioInput.setAttribute('value', answer); radioInput.innerText = answer; list.appendChild(radioInput); var lab = document.createElement("label"); lab.textContent =answer; list.appendChild(lab); }) }) </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试创建一个测验应用程序。 我的JS代码有一些错误,我无法点击按钮或go到下一个问题 - I'm trying to create a quiz app. There are some errors in my JS code, I can not click on the buttons or go to the next questions 当我添加更多问题(JS)时测验消失,怎么办? - Quiz disappears when I add more questions (JS), how? 如何浏览测验中的问题? - How can I navigate questions in a Quiz? 我怎样才能在 axios 的反应中让我的每个测验问题及其在不同页面中的选择 - How can I have each of my my quiz questions and their choices in different pages in react by axios 将测验问题存储在对象数组中 - Storing quiz questions in array of objects 使用 JavaScript,如何在我的测验应用程序上显示一组问题? - Using JavaScript, how can I display a set of questions on my quiz application? 如何在我的测验机器人中显示下一个问题并修复错误? - How can I show the next questions in my quiz bot and fix the error? 如何创建下一个和上一个按钮以使用数组存储作为对象的问题在测验中选择问题? - How can create next and previous button's to select questions in a quiz using an array to store the questions which are objects? Jasmine:如何在我的自定义匹配器中重用其他匹配器 - Jasmine: How can I reuse other matchers in my custom matchers 如何突出显示在线测验的正确和错误答案? - How can I highlight correct and incorrect answers to an online quiz?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM