Получение «неопределенного» в браузере при попытке перенести текст в шаблон HTML через JS и Jquery - PullRequest
0 голосов
/ 05 октября 2019

Я работаю с отдельным документом js под названием «store.js», чтобы сохранить доступное для вставки различное содержимое в HTML-шаблон, определенный в index.js. Я создал множество строк, но они не отображаются.

Я исправил все проблемы в DOM, поэтому кнопка «Пуск» на первом экране без проблем выводит меня на следующий экран.

index.js

function renderQuestion() {
    let question = STORE.question;
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("main").html(questionTemplate);
}

store.js

const STORE = {
    question: [
        {
            questionText: "This is the first question",
            responses: [
                "First response",
                "second response",
                "third response"
            ],
            answer: "first response"
        }
    ]
}

Я пытаюсь показать текст вопроса и ответы из Store.js. После нажатия кнопки «Пуск» я ожидаю увидеть вопрос и ответы внизу.

https://repl.it/@BethanyIleene/Question-App-V3

1 Ответ

1 голос
/ 05 октября 2019

STORE.question - это массив, поэтому вы должны указать, к какому элементу этого массива вы хотите обратиться / визуализировать:

function renderQuestion() {
    let question = STORE.question[0];
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("main").html(questionTemplate);
}

Это всегда будет выбирать первый элемент в массиве, который неимеет большой смысл (имхо). Поэтому я изменил бы, как работает renderQuestion, и ввел бы параметр, который будет представлять вопрос:

function renderQuestion(question) {
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("main").html(questionTemplate);
}

renderQuestion(STORE.question[0]);

. С этим изменением вы можете определить, какой вопрос массива будет добавлен в DOM.

Я бы также изменил имя свойства question с единственного числа на множественное, чтобы оно лучше отражало тот факт, что в массиве может быть / будет более одного вопроса.

store. js

const STORE = {
    questions: [
        {
            questionText: "This is the first question",
            responses: [
                "First response",
                "second response",
                "third response"
            ],
            answer: "first response"
        }, {
            questionText: "This is the second question",
            responses: [
                "First response",
                "second response",
                "third response"
            ],
            answer: "second response"
        }
    ]
}

index.js

function renderQuestion(question) {
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("main").html(questionTemplate);
}

С этими изменениями вы сможете, например, задать один конкретный вопрос с помощью:

renderQuestion(STORE.questions[index]);

const STORE = {
    questions: [
        { questionText: "This is the first question", responses: [ "First response", "second response", "third response"], answer: "first response" },
        { questionText: "This is the second question", responses: [ "First response", "second response", "third response"], answer: "second response" }
    ]
}

function renderQuestion(question) {
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("#main").html(questionTemplate);
}

renderQuestion(STORE.questions[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main"></div>

Или (если заменить .html() на .append()), чтобы напечатать все вопросы из магазина с

STORE.questions.forEach(renderQuestion);

const STORE = {
    questions: [
        { questionText: "This is the first question", responses: [ "First response", "second response", "third response"], answer: "first response" },
        { questionText: "This is the second question", responses: [ "First response", "second response", "third response"], answer: "second response" }
    ]
}

function renderQuestion(question) {
    const questionTemplate = $( `
    <div class="container">
          <p>${question.questionText}<br></p>
          <form>
              <input type="radio">${question.responses}<br>
              <input type="radio">${question.questionOne}<br>
              <input type="radio">${question.question}
            </form>
          <button>Submit</button>
      </div>`);
      $("#main").append(questionTemplate);
}

STORE.questions.forEach(renderQuestion);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main"></div>
...