2017-03-23 1 views
1

퀴즈를위한 정적 HTML 페이지를 만들었습니다. 다음 은 모두 잘 작동JavaScript를 사용하여 HTML 페이지 콘텐츠를 .txt 파일로 저장하는 방법은 무엇입니까?

<style> 
    body { 
font-family: Open Sans; 
} 
#quiz {display:none;} 
#prev {display:none;} 
#start {display:none;} 
#submit{display:none;} 
ul{list-style:outside none none; margin:0px; padding:0px;} 
.question>div>div>div>p{ color: #fff; 
background-color: #337ab7; 
padding: 6px; 
border-radius: 3px;} 
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;} 
</style> 
<body> 
<div class='container question'> 
    <div class='row'> 
     <div class='col col-md-12' id='quiz'> 
     </div> 
    </div> 
</div> 

<div class='container question' > 
<div class='row' id='quiz'> 
</div> 
</div> 
<br/> 
<div class='container'> 
      <a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a> 
      <a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a> 
      <a href='#' class='btn btn-md btn-default' id='start'>Start Over</a> 


     <div class='button' id='submit' style='display:none;'> 
      <input type='text' placeholder='Name' id="inputFileNameToSaveAs"/> 
      <button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button> 
     </div> 
</div> 

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script> 

    <script type="text/javascript"> 


    function saveTextAsFile() 
    { 
    var textToSave = document.getElementById("question").text; 
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"}); 
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob); 
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; 

    var downloadLink = document.createElement("a"); 
    downloadLink.download = fileNameToSaveAs; 
    downloadLink.innerHTML = "Download File"; 
    downloadLink.href = textToSaveAsURL; 
    downloadLink.onclick = destroyClickedElement; 
    downloadLink.style.display = "none"; 
    document.body.appendChild(downloadLink); 

    downloadLink.click(); 
    } 

    function destroyClickedElement(event) 
    { 
     document.body.removeChild(event.target); 
    } 

    function loadFileAsText() 
    { 
     var fileToLoad = document.getElementById("fileToLoad").files[0]; 

     var fileReader = new FileReader(); 
     fileReader.onload = function(fileLoadedEvent) 
     { 
      var textFromFileLoaded = fileLoadedEvent.target.result; 
      document.getElementById("inputTextToSave").value = textFromFileLoaded; 
     }; 
     fileReader.readAsText(fileToLoad, "UTF-8"); 
    } 

       (function() { 
     var questions = [ 
     { 
     question: "Which one is correct?", 
     choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'], 
     correctAnswer: 0 
     }, 

     ]; 

     var questionCounter = 0; //Tracks question number 
     var selections = []; //Array containing user choices 
     var quiz = $('#quiz'); //Quiz div object 

     // Display initial question 
     displayNext(); 

     // Click handler for the 'next' button 
     $('#next').on('click', function (e) { 
     e.preventDefault(); 

     // Suspend click listener during fade animation 
     if(quiz.is(':animated')) {   
      return false; 
     } 
     choose(); 

     // If no user selection, progress is stopped 
     if (isNaN(selections[questionCounter])) { 
      alert('Please make a selection!'); 
     } else { 
      questionCounter++; 
      displayNext(); 
     } 
     }); 

     // Click handler for the 'prev' button 
     $('#prev').on('click', function (e) { 
     e.preventDefault(); 

     if(quiz.is(':animated')) { 
      return false; 
     } 
     choose(); 
     questionCounter--; 
     displayNext(); 
     }); 

     // Click handler for the 'Start Over' button 
     $('#start').on('click', function (e) { 
     e.preventDefault(); 

     if(quiz.is(':animated')) { 
      return false; 
     } 
     questionCounter = 0; 
     selections = []; 
     displayNext(); 
     $('#start').hide(); 
     }); 

     // Animates buttons on hover 
     $('.button').on('mouseenter', function() { 
     $(this).addClass('active'); 
     }); 
     $('.button').on('mouseleave', function() { 
     $(this).removeClass('active'); 
     }); 

     // Creates and returns the div that contains the questions and 
     // the answer selections 
     function createQuestionElement(index) { 
     var qElement = $('<div>', { 
      id: 'question' 
     }); 

     var header = $('<p>Question ' + (index + 1) + '</p>'); 
     qElement.append(header); 

     var question = $('<h3>').append(questions[index].question); 
     qElement.append(question); 

     var radioButtons = createRadios(index); 
     qElement.append(radioButtons); 

     return qElement; 
     } 

     // Creates a list of the answer choices as radio inputs 
     function createRadios(index) { 
     var radioList = $('<ul>'); 
     var item; 
     var input = ''; 
     for (var i = 0; i < questions[index].choices.length; i++) { 
      item = $('<li>'); 
      input = '<input type="radio" name="answer" value=' + i + ' />'; 
      input += questions[index].choices[i]; 
      item.append(input); 
      radioList.append(item); 
     } 
     return radioList; 
     } 

     // Reads the user selection and pushes the value to an array 
     function choose() { 
     selections[questionCounter] = +$('input[name="answer"]:checked').val(); 
     } 

     // Displays next requested element 
     function displayNext() { 
     quiz.fadeOut(function() { 
      $('#question').remove(); 

      if(questionCounter < questions.length){ 
      var nextQuestion = createQuestionElement(questionCounter); 
      quiz.append(nextQuestion).fadeIn(); 
      if (!(isNaN(selections[questionCounter]))) { 
       $('input[value='+selections[questionCounter]+']').prop('checked', true); 
      } 

      // Controls display of 'prev' button 
      if(questionCounter === 1){ 
       $('#prev').show(); 
      } else if(questionCounter === 0){ 

       $('#prev').hide(); 
       $('#next').show(); 
      } 
      }else { 
      var scoreElem = displayScore(); 
      quiz.append(scoreElem).fadeIn(); 
      $('#next').hide(); 
      $('#prev').hide(); 
      $('#start').show(); 
      $('#submit').show(); 
      } 
     }); 
     } 

     // Computes score and returns a paragraph element to be displayed 
     function displayScore() { 
     var score = $('<h4>',{id: 'question'}); 

     var numCorrect = 0; 
     for (var i = 0; i < selections.length; i++) { 
      if (selections[i] === questions[i].correctAnswer) { 
      numCorrect++; 
      } 
     } 

     score.append('You got ' + numCorrect + ' questions out of ' + 
        questions.length + ' right!!!'); 
     return score; 
     } 
    })(); 


    </script> 
     </body> 

내 코드입니다하지만 난 내가 올바른와와 사용자가과 함께 모든 해답을 저장할 .txt 파일 에서 확인 된 라디오 버튼 값과 최종 결과를 저장하려면 틀린.

+0

에 라디오의 가치를 추가 - document.getElementById("question").text;document.getElementById("question").innerHTML;
이어야한다 .value; 배열하고 마지막 점수? – Rico

+0

코드 – stone

+0

을 알려 주실 수 있습니까? 죄송합니다. 당신이 게시 한 코드가 내게 기진 맥진 한 줄, 나는 그것을 읽을 수 없다 :)) – Rico

답변

0

주의 사항 :
- 값이없는 변수 textToSave을 먼저 초기화하십시오.
- choose의 몸에있는 모든 reponses을 저장할 변수 textToSave

그리고 결과

var textToSave=''; 
 
function saveTextAsFile() 
 
    { 
 
    textToSave += ". Final Result : "+document.getElementById("question").innerHTML; 
 
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"}); 
 
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob); 
 
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; 
 

 
    var downloadLink = document.createElement("a"); 
 
    downloadLink.download = fileNameToSaveAs; 
 
    downloadLink.innerHTML = "Download File"; 
 
    downloadLink.href = textToSaveAsURL; 
 
    downloadLink.onclick = destroyClickedElement; 
 
    downloadLink.style.display = "none"; 
 
    document.body.appendChild(downloadLink); 
 

 
    downloadLink.click(); 
 
    } 
 

 
    function destroyClickedElement(event) 
 
    { 
 
     document.body.removeChild(event.target); 
 
    } 
 

 
    function loadFileAsText() 
 
    { 
 
     var fileToLoad = document.getElementById("fileToLoad").files[0]; 
 

 
     var fileReader = new FileReader(); 
 
     fileReader.onload = function(fileLoadedEvent) 
 
     { 
 
      var textFromFileLoaded = fileLoadedEvent.target.result; 
 
      document.getElementById("inputTextToSave").value = textFromFileLoaded; 
 
     }; 
 
     fileReader.readAsText(fileToLoad, "UTF-8"); 
 
    } 
 

 
       (function() { 
 
     var questions = [ 
 
     { 
 
     question: "Which one is correct?", 
 
     choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'], 
 
     correctAnswer: 0 
 
     }, 
 

 
     ]; 
 

 
     var questionCounter = 0; //Tracks question number 
 
     var selections = []; //Array containing user choices 
 
     var quiz = $('#quiz'); //Quiz div object 
 

 
     // Display initial question 
 
     displayNext(); 
 

 
     // Click handler for the 'next' button 
 
     $('#next').on('click', function (e) { 
 
     e.preventDefault(); 
 

 
     // Suspend click listener during fade animation 
 
     if(quiz.is(':animated')) {   
 
      return false; 
 
     } 
 
     choose(); 
 

 
     // If no user selection, progress is stopped 
 
     if (isNaN(selections[questionCounter])) { 
 
      alert('Please make a selection!'); 
 
     } else { 
 
      questionCounter++; 
 
      displayNext(); 
 
     } 
 
     }); 
 

 
     // Click handler for the 'prev' button 
 
     $('#prev').on('click', function (e) { 
 
     e.preventDefault(); 
 

 
     if(quiz.is(':animated')) { 
 
      return false; 
 
     } 
 
     choose(); 
 
     questionCounter--; 
 
     displayNext(); 
 
     }); 
 

 
     // Click handler for the 'Start Over' button 
 
     $('#start').on('click', function (e) { 
 
     e.preventDefault(); 
 

 
     if(quiz.is(':animated')) { 
 
      return false; 
 
     } 
 
     questionCounter = 0; 
 
     selections = []; 
 
     displayNext(); 
 
     $('#start').hide(); 
 
     }); 
 

 
     // Animates buttons on hover 
 
     $('.button').on('mouseenter', function() { 
 
     $(this).addClass('active'); 
 
     }); 
 
     $('.button').on('mouseleave', function() { 
 
     $(this).removeClass('active'); 
 
     }); 
 

 
     // Creates and returns the div that contains the questions and 
 
     // the answer selections 
 
     function createQuestionElement(index) { 
 
     var qElement = $('<div>', { 
 
      id: 'question' 
 
     }); 
 

 
     var header = $('<p>Question ' + (index + 1) + '</p>'); 
 
     qElement.append(header); 
 

 
     var question = $('<h3>').append(questions[index].question); 
 
     qElement.append(question); 
 

 
     var radioButtons = createRadios(index); 
 
     qElement.append(radioButtons); 
 

 
     return qElement; 
 
     } 
 

 
     // Creates a list of the answer choices as radio inputs 
 
     function createRadios(index) { 
 
     var radioList = $('<ul>'); 
 
     var item; 
 
     var input = ''; 
 
     for (var i = 0; i < questions[index].choices.length; i++) { 
 
      item = $('<li>'); 
 
      input = '<input type="radio" name="answer" value=' + i + ' />'; 
 
      input += questions[index].choices[i]; 
 
      item.append(input); 
 
      radioList.append(item); 
 
     } 
 
     return radioList; 
 
     } 
 

 
     // Reads the user selection and pushes the value to an array 
 
     function choose() { 
 
     selections[questionCounter] = +$('input[name="answer"]:checked').val(); 
 
     textToSave += "Choosen Value : "+selections[questionCounter]; 
 
     } 
 

 
     // Displays next requested element 
 
     function displayNext() { 
 
     quiz.fadeOut(function() { 
 
      $('#question').remove(); 
 

 
      if(questionCounter < questions.length){ 
 
      var nextQuestion = createQuestionElement(questionCounter); 
 
      quiz.append(nextQuestion).fadeIn(); 
 
      if (!(isNaN(selections[questionCounter]))) { 
 
       $('input[value='+selections[questionCounter]+']').prop('checked', true); 
 
      } 
 

 
      // Controls display of 'prev' button 
 
      if(questionCounter === 1){ 
 
       $('#prev').show(); 
 
      } else if(questionCounter === 0){ 
 

 
       $('#prev').hide(); 
 
       $('#next').show(); 
 
      } 
 
      }else { 
 
      var scoreElem = displayScore(); 
 
      quiz.append(scoreElem).fadeIn(); 
 
      $('#next').hide(); 
 
      $('#prev').hide(); 
 
      $('#start').show(); 
 
      $('#submit').show(); 
 
      } 
 
     }); 
 
     } 
 

 
     // Computes score and returns a paragraph element to be displayed 
 
     function displayScore() { 
 
     var score = $('<h4>',{id: 'question'}); 
 

 
     var numCorrect = 0; 
 
     for (var i = 0; i < selections.length; i++) { 
 
      if (selections[i] === questions[i].correctAnswer) { 
 
      numCorrect++; 
 
      } 
 
     } 
 

 
     score.append('You got ' + numCorrect + ' questions out of ' + 
 
        questions.length + ' right!!!'); 
 
     return score; 
 
     } 
 
    })();
<style> 
 
    body { 
 
font-family: Open Sans; 
 
} 
 
#quiz {display:none;} 
 
#prev {display:none;} 
 
#start {display:none;} 
 
#submit{display:none;} 
 
ul{list-style:outside none none; margin:0px; padding:0px;} 
 
.question>div>div>div>p{ color: #fff; 
 
background-color: #337ab7; 
 
padding: 6px; 
 
border-radius: 3px;} 
 
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;} 
 
</style> 
 
<body> 
 
<div class='container question'> 
 
    <div class='row'> 
 
     <div class='col col-md-12' id='quiz'> 
 
     </div> 
 
    </div> 
 
</div> 
 

 
<div class='container question' > 
 
<div class='row' id='quiz'> 
 
</div> 
 
</div> 
 
<br/> 
 
<div class='container'> 
 
      <a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a> 
 
      <a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a> 
 
      <a href='#' class='btn btn-md btn-default' id='start'>Start Over</a> 
 

 

 
     <div class='button' id='submit' style='display:none;'> 
 
      <input type='text' placeholder='Name' id="inputFileNameToSaveAs"/> 
 
      <button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button> 
 
     </div> 
 
</div> 
 

 
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script> 
 

 

 
     </body>

+0

thx는 저에게 효과적입니다. – stone

0

최종 사용자가 아닌 사용자가 직접 데이터를 저장한다고 가정합니다.

당신은 TXT 파일을 생성 및 다운로드 찾고 있다면 - 당신은

당신은 직접 파일에 답이나 어떤 데이터를 저장할 수 없습니다 사가르 V.에서 답을 참조 할 수 있습니다 웹 브라우저에서 자바 스크립트를 사용하여 .

당신은 아마 Node.js를, PHP 또는 자바 우선 형식으로 JSON과 같은 특정 구조의 답변에, 작은 서버를 neeed하고 매개 변수를 구문 분석하고 저장할 POST 요청 메소드 매개 변수로 서버에서

그것을 세네 필요한 파일

0
function downloadFile(filename, content) { 
    var element = document.createElement('a'); 
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content)); 
    element.setAttribute('download', filename); 

    element.style.display = 'none'; 
    document.body.appendChild(element); 

    element.click(); 

    document.body.removeChild(element); 
} 
관련 문제