首页 > 解决方案 > 试图将我的 JavaScript 转换为 JQuery

问题描述

我正在尝试将我的 Javascript 代码转换为 JQuery,但我知道在调用该函数时我做错了。在尝试按名称调用无线电元素时,我很难确切知道该放什么。

原始 Javascript 有效,但我不确定如何让 JQuery 版本正常工作。

索引 HTML

<!DOCTYPE html>
<html lang="en"> 
<head>        
<title>Disney Quiz</title>
<meta charset="utf-8">    
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script
</head>

<body>    
<header><h1>Disney Quiz</h1></header>

<main>

<p>Click on the correct answer for each question and submit your results.</p>

<form>
        <fieldset>
           <legend>Trivia Questions</legend>
           <label> Enter your Name</label> <input type="text" id="myText" name="fieldName" value=""><br>
            <section id="radio1">
                <p> Question 1) What was Walt Disney's first character he created?</p>
                <input type="radio" name="question0" value="A">Oswald the Lucky Rabbit<br>
                <input type="radio" name="question0" value="B">Donald Duck<br>
                <input type="radio" name="question0" value="C">Mickey Mouse<br>
                <input type="radio" name="question0" value="D">Goofy<br>
                <p id="flag0"><p>
            </section>
            <section id="radio2">
                <p> Question 2) Snow White was the first ____ to ever be produced successfully.</p>
                <input type="radio" name="question1" value="A">Movie<br>
                <input type="radio" name="question1" value="B">Live-Action<br>
                <input type="radio" name="question1" value="C">Cel-animated Film<br>
                <input type="radio" name="question1" value="D">Cartoon<br>
                <p id="flag1"><p>
            </section>
            <section id="radio3">
                <p> Question 3) Walt left a big impression when he had created ____ films for the U.S. government</p>
                <input type="radio" name="question2" value="A">Peacemaker<br>
                <input type="radio" name="question2" value="B">Political<br>
                <input type="radio" name="question2" value="C">World War II<br>
                <input type="radio" name="question2" value="D">Religious<br>
                <p id="flag2"><p>
            </section>
            <section id="radio4">
                    <p> Question 4) Which of the following is true?</p>
                <input type="radio" name="question3" value="A">Disney at first wanted to become a filmmaker<br>
                <input type="radio" name="question3" value="B">Disney has made multiple controversial cartoons.<br>
                <input type="radio" name="question3" value="C">Disney holds the record for most individual Oscar wins.<br>
                <input type="radio" name="question3" value="D">Heart failure was the cause of Disney's death.<br>
                <p id="flag3"><p>
            </section>
            <section id="radio5">
                    <p> Question 5) Which of the following has been rumored to happen to Walt Disney after his death?</p>
                <input type="radio" name="question4" value="A">Faked his death<br>
                <input type="radio" name="question4" value="B">Cremated<br>
                <input type="radio" name="question4" value="C">Buried<br>
                <input type="radio" name="question4" value="D">Cryogenically frozen<br>
                <p id="flag4"><p>
            </section>
                 <br>

            <button type="button">Show Results</button>
            <p id="results"></p>
         </fieldset>
       </form>
</main>
<aside>

</aside>
<footer>    <p align="center">  Project 4 - Fall 2018  </p>  </footer>    
</body>
</html>

原始 JavaScript

var answers = ["A","C","B","C","D"], 
    total = answers.length;

function getCheckedValue(radioName)
{
    var radios = document.getElementsByName(radioName);

    for (var y = 0; y < radios.length; y++)
    {
      if(radios[y].checked)
      {
          return radios[y].value; 
      }
    }
}

function getScore()
{
  var score = 0;

  for (var i = 0; i < total; i++)
  {
      document.getElementById("flag"+i).innerHTML = "";
      if(getCheckedValue("question"+i) == answers[i])
      {
          score += 1;
      }
      else if(getCheckedValue("question"+i) != answers[i])
      {
          document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
      }


  }


  return score;
}

function returnScore()
{
    var x = document.getElementById("myText").value;
    document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}

jQuery

var answers = ["A","C","B","C","D"], 
    total = answers.length;

$(function getCheckedValue()
{
    var radios = $('[name="question"]');

    for (var y = 0; y < radios.length; y++)
    {
      if(radios[y].checked)
      {
          return radios[y].value; 
      }
    }
});

$(':button').on('click', function getScore()
{
  var score = 0;

  for (var i = 0; i < total; i++)
  {
      $("flag"+i).innerHTML = "";
      if(getCheckedValue("question"+i) == answers[i])
      {
          score += 1;
      }
      else if(getCheckedValue("question"+i) != answers[i])
      {
          $("flag"+i).innerHTML = "Your answer is incorrect.";
      }


  }

  return score;
});

$(function returnScore()
{
    var x = $("myText").value;
    $("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
});

标签: javascriptjqueryhtml

解决方案


你不需要把函数定义放在里面$(...),只要把它放在顶层,就像在你的普通 JS 版本中一样。$(...)适用于需要在加载 DOM 后运行的代码,但您无需等待定义函数。它还将调用您在那里定义的函数,而不仅仅是定义它们。

的 jQuery 版本getCheckValue()没有使用该参数,您需要添加它。

ID 的选择器需要以 . 开头#

function getCheckedValue(radioname)
{
    return $(`[name="${radioname}"]:checked:first`).val();
}

getScore你的else if情况下是相反的if情况。所以你应该只使用else. 并且 jQuery 使用.html().text()函数来填充一个元素,你没有分配给.innerHTML.

$(':button').on('click', function getScore()
{
  var score = 0;

  for (var i = 0; i < total; i++)
  {
      $("flag"+i).innerHTML = "";
      if(getCheckedValue("question"+i) == answers[i])
      {
          score += 1;
      }
      else
      {
          $("#flag"+i).text("Your answer is incorrect.");
      }


  }
  return score;
});

function returnScore()
{
    var x = $("#myText").value;
    $("#results").html(x + ", your score is " + getScore() + "/" + total);
}

在 HTML 中,您需要更改加载脚本的顺序:

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>    
<script src="scripts/quiz.js"></script>

由于quiz.js使用 jQuery,因此必须先加载 jQuery。


推荐阅读