首页 > 解决方案 > 如何在 jQuery 中选择正确的获取元素

问题描述

在我下面的工作中,我获取了串行10数据,并在按钮中显示了这些数据。

当我单击按钮时,所需的结果是显示下一个选项。

但是当我尝试这个时,$(".choice")选择器可能无法正常工作。

下面这个按钮是js生成的,是这个问题的原因吗?

<button class='choice'>"+arr[i]+"</button>

如果有人有任何意见,请告诉我。

谢谢

// const fetch = require("node-fetch");

let clicked=0;

var apikey="https://opentdb.com/api.php?amount=10&type=multiple";

$(".start").on("click",function(){

  
  fetch(apikey)
  fetch(apikey)
    .then(response => response.json())
    .then(json => {
      
      console.log(json);
      
      display(json,0);
      
      $(".choice").on("click",function() {
          clicked++;
          console.log("#");
          console.log("clicked",clicked);
          display(json,clicked);
      });
    });
});



function display(json,clicked){
  
      const arr = [json.results[clicked].correct_answer].concat(json.results[clicked].incorrect_answers);
  
      let html="";
      
      for (let i=0;i<arr.length; i++){
        html+= "<button class='choice'>"+arr[i]+"</button><br>";
      }
      document.querySelector('.btn').innerHTML = html;
}
<!DOCTYPE html>


<html>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script data-main="js/main.js" src="bower_components/requirejs/require.js"></script>

        
        <div class="btn">       
            <button type="button" class="start">Start</button>
        </div>
    
    <script type="text/javascript" src="main.js"></script>
    
</html>

标签: javascriptjquery

解决方案


我设置了我从您的代码中理解的游戏(没有 jQuery)。

  1. 数据到了才可以开始
  2. 选择(按钮)被打乱,所以它并不总是第一个获胜(打乱来自这里:如何随机化(打乱)JavaScript数组?
  3. 游戏会记录正确答案

也许它看起来比你做的要复杂一些,但是(几乎)一切都被分离到函数中,所以修改它们更容易(显示、数据和游戏逻辑是解耦的)

// used variables
const url = "https://opentdb.com/api.php?amount=10&type=multiple"
const startBtn = document.getElementById('btn-start')
const progress = document.getElementById('progress')
const question = document.getElementById('question')
const choices = document.getElementById('choices')
let results = ''
let questionId = 0
let correct = 0

// fetching the data
const fetchData = async(url) => {
  // try-catch for handling fetch errors
  try {
    const resp = await fetch(url)
    const json = await resp.json()
    // only returning the questions and results
    return json.results
  } catch (err) {
    console.log(err)
  }
}

// only allow clicks on start button if the data has arrived
(async function() {
  results = await fetchData(url)
  startBtn.removeAttribute('disabled')
})();

// starting off with the game
startBtn.addEventListener('click', function(e) {
  this.classList.add('started')
  nextQuestion(correct, results, questionId)
})

// setting up the next question
const nextQuestion = (correct, results, questionId) => {
  // set progress indicator
  progress.innerHTML = progressText(correct, results.length)

  // set question string
  question.innerHTML = results[questionId].question

  // set buttons to click
  choices.innerHTML = setChoices(results[questionId].correct_answer, results[questionId].incorrect_answers)

  // adding event listeners to buttons
  const answerBtns = document.querySelectorAll(".answer")
  answerBtns.forEach(e => {
    e.addEventListener('click', function(e) {
      const answer = e.target.getAttribute('data-val')

      // checking for correct answer (and existence of next answer)
      if (results[questionId] && answer === results[questionId].correct_answer) {
        correct++
      }
      questionId++

      // creating next question 'scene'
      if (questionId < results.length) {
        nextQuestion(correct, results, questionId)
      }
    })
  })
}

// creating progress indicator string
const progressText = (correct, all) => {
  return `${correct}/${all}`
}

// setting choice buttons
const setChoices = (correct, incorrect) => {
  let answers = shuffleArray([correct, ...incorrect])
  let html = ''
  answers.forEach(e => {
    html += `<button class="answer" data-val="${e}">${e}</button><br />`
  })
  return html
}

// shuffling the choice array for a little fun
const shuffleArray = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array
}
.start.started {
  display: none;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="btn">
  <button id="btn-start" type="button" class="start" disabled>Start</button>
  <div id="game">
    <h3 id="progress"></h3>
    <h2 id="question"></h2>
    <div id="choices"></div>
  </div>
</div>


推荐阅读