2015-11-04 3 views
0

Я делаю эту викторину для своего экономического класса. Я решил сделать это в java-скрипте. после запуска моего скрипта страница обновляется. Предполагается, что страница изменит цвет фона входных тегов. Что я делаю не так? Первый блок переменных собирает информацию, второй - переменные в нижнем регистре. Код работает отлично, когда он находится в html-файле, но я хочу, чтобы он был внешним javascript.Моя веб-страница обновляется после запуска javascript

EDIT: Я сделал то, что сказал Саймон, удалив [return false;] из моего js и изменив мой onclick на [onclick = "return checkAnswers();"], но я все еще испытываю ту же проблему ,

EDIT: Я сделал то, что сказал Дункан, и теперь он отлично работает, спасибо!

HTML:

<!DOCTYPE html /> 

<html> 
    <head> 
     <title>Chapter 2</title> 

     <style type="text/css"> 
     input{ 
      width:150px; 
      border:none; 
      border-bottom:solid 1px #C0C0C0; 
      text-align:center; 
     } 
     h1, h3, body{ 
      text-align:center; 
     } 
     div{ 
      border:double 3px #C0C0C0; 
      margin:5px; 
      padding:10px; 
      border-radius:5%; 
      text-align:left; 
     } 
     a:link, a:visited{ 
      color:#0000FF; 
     } 
     a:hover{ 
      color:#CC00FF; 
      font-size:1.5em; 
     } 
     #sect2def2{ 
      width:200px; 
     } 
     </style> 

     <script type="text/javascript" src="javascript\script.js"></script> 
    </head> 
    <body> 
     <h1>Chapter 3</h1> 
     <form> 
      <a name="notes"></a><h3>Notes</h3> 
      <div id="section1"> 
       <h3>Section 1</h3> 
       <input type="text" id="sect1def1"></input> is another name for capitalism, an economic system based on private ownership of productive resources. 
       <br /> 
       <input type="text" id="sect1def2"></input> is the ability of everyone to take part in the market by free choice. 
       <br /> 
       <input type="text" id="sect1def3"></input> is a situation in which everyone has the same economic rights under the law. 
       <br /> 
       A <input type="text" id="sect1def4"></input> is a situation in which people decide which legal agreements to enter into. 
       <br /> 
       The <input type="text" id="sect1def5"></input> is the force that encourages people and organizations to improve their material well being from economic activities. 
      </div> 
      <div id="section 2"> 
       <h3>Section 2</h3> 
       <input type="text" id="sect2def1"></input> is the money left over after the costs of producing a good or service have been subtracted from the revenue gained by selling that good or service. 
       <br /> 
       A <input type="text" id="sect2def2"></input> is a free enterprise economic system with some government involvement. 
      </div> 
      <div id="section 3"> 
       <h3>Section 3</h3> 
       <input type="text" id="sect3def1"></input> occurs when people who are not part of a marketplace interaction benefit from it or pay part of its costs. 
       <br /> 
       <input type="text" id="sect3def2"></input> are products provided by federal, state, and local governments and consumed by the public as a group. 
       <br /> 
       A <input type="text" id="sect3def3"></input> is a person who avoids paying for a good or service but who benefits from that good or service anyway. 
       <br /> 
       The <input type="text" id="sect3def4"></input> consists of all the goods and services that are necessary for the functioning of society. 
       <br /> 
       An <input type="text" id="sect3def5"></input> is a side effect of a product that affects someone other than the producer or the buyer. 
       <br /> 
       A <input type="text" id="sect3def6"></input> is an externality that imposes costs on people who were not involved in the original economic activity. 
       <br /> 
       A <input type="text" id="sect3def7"></input> is an externality that creates benefits for people who were not involved in the original economic activity. 
       <br /> 
       A <input type="text" id="sect3def8"></input> is a government payment that helps cover the cost of an economic activity that has the potential to benefit the public as a whole. 
       <br /> 
       The <input type="text" id="sect3def9"></input> consists of government programs designed to protect people from economic hardships. 
       <br /> 
       <input type="text" id="sect3def10"></input> are transfers of income from one person or group to another even though the receiver does not provide anything in return. 
       <br /> 
       A <input type="text" id="sect3def11"></input> is a transfer payment in which the government transfers income from taxpayers to recipients who do not provide anything in return. 
      </div> 
      <button id="notesButton" onclick="checkAnswers();">Submit</button> 
     </form> 
    </body> 
</html> 

JavaScript:

function checkAnswers() { 
    var s1d1 = document.getElementById("sect1def1").value; 
    var s1d2 = document.getElementById("sect1def2").value; 
    var s1d3 = document.getElementById("sect1def3").value; 
    var s1d4 = document.getElementById("sect1def4").value; 
    var s1d5 = document.getElementById("sect1def5").value; 
    var s2d1 = document.getElementById("sect2def1").value; 
    var s2d2 = document.getElementById("sect2def2").value; 
    var s3d1 = document.getElementById("sect3def1").value; 
    var s3d2 = document.getElementById("sect3def2").value; 
    var s3d3 = document.getElementById("sect3def3").value; 
    var s3d4 = document.getElementById("sect3def4").value; 
    var s3d5 = document.getElementById("sect3def5").value; 
    var s3d6 = document.getElementById("sect3def6").value; 
    var s3d7 = document.getElementById("sect3def7").value; 
    var s3d8 = document.getElementById("sect3def8").value; 
    var s3d9 = document.getElementById("sect3def9").value; 
    var s3d10 = document.getElementById("sect3def10").value; 
    var s3d11 = document.getElementById("sect3def11").value; 

    var s1d1L = s1d1.toLowerCase(); 
    var s1d2L = s1d2.toLowerCase(); 
    var s1d3L = s1d3.toLowerCase(); 
    var s1d4L = s1d4.toLowerCase(); 
    var s1d5L = s1d5.toLowerCase(); 
    var s2d1L = s2d1.toLowerCase(); 
    var s2d2L = s2d2.toLowerCase(); 
    var s3d1L = s3d1.toLowerCase(); 
    var s3d2L = s3d2.toLowerCase(); 
    var s3d3L = s3d3.toLowerCase(); 
    var s3d4L = s3d4.toLowerCase(); 
    var s3d5L = s3d5.toLowerCase(); 
    var s3d6L = s3d6.toLowerCase(); 
    var s3d7L = s3d7.toLowerCase(); 
    var s3d8L = s3d8.toLowerCase(); 
    var s3d9L = s3d9.toLowerCase(); 
    var s3d10L = s3d10.toLowerCase(); 
    var s3d11L = s3d11.toLowerCase(); 

    if (s1d1L=="free enterprise system"){ 
     document.getElementById("sect1def1").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect1def1").style.backgroundColor = "#FF0000"; 
    } 
    if (s1d2L=="open opportunity"){ 
     document.getElementById("sect1def2").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect1def2").style.backgroundColor = "#FF0000"; 
    } 
    if (s1d3L=="legal equality"){ 
     document.getElementById("sect1def3").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect1def3").style.backgroundColor = "#FF0000"; 
    } 
    if (s1d4L=="free contract"){ 
     document.getElementById("sect1def4").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect1def4").style.backgroundColor = "#FF0000"; 
    } 
    if (s1d5L=="profit motive"){ 
     document.getElementById("sect1def5").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect1def5").style.backgroundColor = "#FF0000"; 
    } 
    if (s2d1L=="profit"){ 
     document.getElementById("sect2def1").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect2def1").style.backgroundColor = "#FF0000"; 
    } 
    if (s2d2L=="modified free enterprise economy"){ 
     document.getElementById("sect2def2").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect2def2").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d1L=="market failure"){ 
     document.getElementById("sect3def1").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def1").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d2L=="public goods"){ 
     document.getElementById("sect3def2").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def2").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d3L=="free rider"){ 
     document.getElementById("sect3def3").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def3").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d4L=="infrastructure"){ 
     document.getElementById("sect3def4").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def4").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d5L=="externality"){ 
        document.getElementById("sect3def5").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def5").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d6L=="negative externality"){ 
     document.getElementById("sect3def6").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def6").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d7L=="positive externality"){ 
     document.getElementById("sect3def7").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def7").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d8L=="subsidy"){ 
     document.getElementById("sect3def8").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def8").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d9L=="safety net"){ 
     document.getElementById("sect3def9").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def9").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d10L=="transfer payments"){ 
     document.getElementById("sect3def10").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def10").style.backgroundColor = "#FF0000"; 
    } 
    if (s3d11L=="public transfer payment"){ 
     document.getElementById("sect3def11").style.backgroundColor = "#00FF00"; 
    } else { 
     document.getElementById("sect3def11").style.backgroundColor = "#FF0000"; 
    } 
    return false; 
} 
+0

Почему вы так говорите? –

+0

Есть всевозможные способы, которыми вы могли бы сократить количество кода, который у вас есть. Эти отдельные переменные должны быть частью массива, инициализированного циклом. Эти тесты могут быть сведены к просмотру карты. Ваша непосредственная проблема, вероятно, в ответе от @Simon. – Pointy

+0

Я новичок в javascript, и я знаю, что есть более простой способ сделать это, но я ограничен своими знаниями. –

ответ

2

Вы не возвращают ложные в обработчике OnClick (вы только делаете это в вашей функции). Нечто подобное могло бы быть прекрасно:

<button id="notesButton" onclick="return checkAnswers();">Submit</button> 

EDIT: Это даже лучше, чтобы связать функцию onsubmit формы, а в случае кто-то отправляет форму с клавиатуры без использования вашей кнопки.

+0

Я удалил «return false»; и добавил «onclick =» return checkAnswers(); »« но у меня все еще такая же проблема. –

+0

Вам нужны оба. Без возврата false в методе. Метод ничего не возвращает. С помощью функции return checkAnswers() в обработчике on-click он передает возвращаемое значение из метода в событие click кнопки. возвращая false обработчику событий клика. Он останавливает его от запуска функции по умолчанию. –

+0

Спасибо Дункан! –

Смежные вопросы