#javascript #html #database #sqlite
#javascript #HTML #База данных #sqlite
Вопрос:
ниже приведен код для функции проверки, которая сохранит значение переменной ‘c’ и document.write
отобразит его на пустой странице. я пытался найти способ передать это в свой html, чтобы я мог создать экран оценки и отобразить ту же строку, что и здесь, в формате html, но я не могу заставить функцию или переменную проходить, как бы я ни старался.
function check() {
let c=0
const q1=document.quiz.question1.value
const q2=document.quiz.question2.value
const q3=document.quiz.question3.value
const q4=document.quiz.question4.value
const q5=document.quiz.question5.value
if(q1==='1') {
c
}
if(q2==='1') {
c
}
if(q3==='1') {
c
}
if(q4==='1') {
c
}
if(q5==='1') {
c
}
document.write('<h1>You scored ' c '
and your average was ' c/10*100 '%</h1>')
}
ниже приведен html-код, который я пробовал, но я не понимаю, как экспортировать параметры функции
<section>
<h2> Welcome
<script type="text/javascript">
document.write('You scored ' c
'and your average was ' c/10*100 '%' ")
</script>
</h2>
</section>
я знаю, что это может не быть частью вопроса или может быть дополнительным шагом, но было бы проще сохранить это значение c в базе данных, а затем извлечь из базы данных в html-код? в любом случае мне нужно иметь возможность сохранять эту оценку вместе с именем в базе данных, поэтому, возможно, было бы проще заполнить базу данных значениями, а затем извлечь их оттуда с помощью запроса select или тега handlebar (поскольку у меня есть index.handlebar, на котором я буду отображать оценкис другими данными). извините за длинный вопрос, но я боролся со стороной базы данных, поэтому мне нужно быстро решить эти проблемы. Любая помощь приветствуется 🙂
Извините за длинные объемы кода, но я не был уверен, что вам нужно понять, что я пытаюсь сделать. Приведенный ниже код сохраняет значение внутри переключателя, а переменная c автоматически увеличивает 1, а затем функция внизу под названием «check3 ()» запускает приращение для каждого значения, а затем выполняет вычисление. что я хочу сделать, так это отобразить то же самое вычисление оператора на той же странице, если это необходимо, но оно должно иметь тот же css, что и страница текущей страницы.
<main class='questionsContainer'>
<form name='quiz' id='quiz'>
<!-- first set -->
<section id='questions6' style="min-height: 190px">
<h3>{{this.Question1}}</h3>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question1" value="0">Emacs</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question1" value="0">Notepad </h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question1" value="1">Vim</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question1" value="0">Bash</h3><br>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(6, 7)">next</button>
</section>
<!-- second set -->
<section id='questions7' style="min-height: 190px">
<h2>{{this.Question2}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question2" value="1">Nothing</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question2" value="0">
Java Development Kit 1.8 or newer</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question2" value="0">Apache Maven</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question2" value="0">
Jakarta Enterprise Edition web profile compliant server</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(7, 6)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(7, 8)">next</button>
</section>
<!-- Third set -->
<section id='questions8' style="min-height: 190px">
<h2>{{this.Question3}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question3" value="0">username and IP address</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question3" value="0">username and password</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question3" value="0">email address and password</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question3" value="1">username and email address</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(8, 7)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(8, 9)">next</button>
</section>
<!-- fourth set -->
<section id='questions9' style="min-height: 190px"style="min-height: 190px">
<h2>{{this.Question4}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question4" value="0">System</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question4" value="0">Local</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question4" value="1">User</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question4" value="0">Global</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(9, 8)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(9, 10)">next</button>
</section>
<!-- fifth set -->
<section id='questions10' style="min-height: 190px">
<h2>{{this.Question5}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question5" value="0">Junio C. Hamano</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question5" value="0">James Gosling</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question5" value="1">Linus Torvalds</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question5" value="0">Kohsuke Kawaguchi</h3> <br>
<button style="position: absolute; bottom: 15px; left: 25%;"
type='button' onclick="previousQuestion(10, 9)">previous</button>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button'
onclick="nextQuestion(10, 6)">Back to Question 1</button>
<input style="position: absolute; bottom: 15px; right:20%;" type="button"
value="Check Your Grade!" onclick="check3(check1, check2)">
</section>
{{/each}}
</form>
</main>
Комментарии:
1. Где ваш JavaScript? Это в отдельном файле JS?
2. да, я импортировал файл javascript, чтобы использовать некоторые функции кнопок, которые скрывают и показывают элементы, я попытался импортировать переменную, используя встроенный код внутри самого основного тега, и это не сработало. я знаю, что файл был импортирован правильно, потому что кнопки работают нормально.
Ответ №1:
Похоже, вы хотите взять document.write и отобразить его на экране.
function myFunction() {
//Create the HTML ELEMENT
const msgDiv = document.createElement('h1');
// create the message you want to display
msgDiv.innerHTML = `<span>$ You scored {c} and you average was {c/10*100}%</span>
#javascript #html #database #sqlite
#javascript #HTML #База данных #sqlite
Вопрос:
ниже приведен код для функции проверки, которая сохранит значение переменной 'c' и document.write
отобразит его на пустой странице. я пытался найти способ передать это в свой html, чтобы я мог создать экран оценки и отобразить ту же строку, что и здесь, в формате html, но я не могу заставить функцию или переменную проходить, как бы я ни старался.
function check() {
let c=0
const q1=document.quiz.question1.value
const q2=document.quiz.question2.value
const q3=document.quiz.question3.value
const q4=document.quiz.question4.value
const q5=document.quiz.question5.value
if(q1==='1') {
c
}
if(q2==='1') {
c
}
if(q3==='1') {
c
}
if(q4==='1') {
c
}
if(q5==='1') {
c
}
document.write('<h1>You scored ' c '
and your average was ' c/10*100 '%</h1>')
}
ниже приведен html-код, который я пробовал, но я не понимаю, как экспортировать параметры функции
<section>
<h2> Welcome
<script type="text/javascript">
document.write('You scored ' c
'and your average was ' c/10*100 '%' ")
</script>
</h2>
</section>
я знаю, что это может не быть частью вопроса или может быть дополнительным шагом, но было бы проще сохранить это значение c в базе данных, а затем извлечь из базы данных в html-код? в любом случае мне нужно иметь возможность сохранять эту оценку вместе с именем в базе данных, поэтому, возможно, было бы проще заполнить базу данных значениями, а затем извлечь их оттуда с помощью запроса select или тега handlebar (поскольку у меня есть index.handlebar, на котором я буду отображать оценкис другими данными). извините за длинный вопрос, но я боролся со стороной базы данных, поэтому мне нужно быстро решить эти проблемы. Любая помощь приветствуется 🙂
Извините за длинные объемы кода, но я не был уверен, что вам нужно понять, что я пытаюсь сделать. Приведенный ниже код сохраняет значение внутри переключателя, а переменная c автоматически увеличивает 1, а затем функция внизу под названием "check3 ()" запускает приращение для каждого значения, а затем выполняет вычисление. что я хочу сделать, так это отобразить то же самое вычисление оператора на той же странице, если это необходимо, но оно должно иметь тот же css, что и страница текущей страницы.
<main class='questionsContainer'>
<form name='quiz' id='quiz'>
<!-- first set -->
<section id='questions6' style="min-height: 190px">
<h3>{{this.Question1}}</h3>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question1" value="0">Emacs</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question1" value="0">Notepad </h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question1" value="1">Vim</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question1" value="0">Bash</h3><br>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(6, 7)">next</button>
</section>
<!-- second set -->
<section id='questions7' style="min-height: 190px">
<h2>{{this.Question2}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question2" value="1">Nothing</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question2" value="0">
Java Development Kit 1.8 or newer</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question2" value="0">Apache Maven</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question2" value="0">
Jakarta Enterprise Edition web profile compliant server</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(7, 6)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(7, 8)">next</button>
</section>
<!-- Third set -->
<section id='questions8' style="min-height: 190px">
<h2>{{this.Question3}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question3" value="0">username and IP address</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question3" value="0">username and password</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question3" value="0">email address and password</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question3" value="1">username and email address</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(8, 7)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(8, 9)">next</button>
</section>
<!-- fourth set -->
<section id='questions9' style="min-height: 190px"style="min-height: 190px">
<h2>{{this.Question4}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question4" value="0">System</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question4" value="0">Local</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question4" value="1">User</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question4" value="0">Global</h3><br>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button' onclick="previousQuestion(9, 8)">previous</button>
<button style="position: absolute; bottom: 15px;" type='button' onclick="nextQuestion(9, 10)">next</button>
</section>
<!-- fifth set -->
<section id='questions10' style="min-height: 190px">
<h2>{{this.Question5}}</h2>
<!-- first choice -->
<h3><input type="radio" id="option1" name="question5" value="0">Junio C. Hamano</h3>
<!-- second choice -->
<h3><input type="radio" id="option2" name="question5" value="0">James Gosling</h3>
<!-- third choice -->
<h3><input type="radio" id="option3" name="question5" value="1">Linus Torvalds</h3>
<!-- fourth choice -->
<h3><input type="radio" id="option4" name="question5" value="0">Kohsuke Kawaguchi</h3> <br>
<button style="position: absolute; bottom: 15px; left: 25%;"
type='button' onclick="previousQuestion(10, 9)">previous</button>
<button style="position: absolute; bottom: 15px; left: 35%;" type='button'
onclick="nextQuestion(10, 6)">Back to Question 1</button>
<input style="position: absolute; bottom: 15px; right:20%;" type="button"
value="Check Your Grade!" onclick="check3(check1, check2)">
</section>
{{/each}}
</form>
</main>
Комментарии:
1. Где ваш JavaScript? Это в отдельном файле JS?
2. да, я импортировал файл javascript, чтобы использовать некоторые функции кнопок, которые скрывают и показывают элементы, я попытался импортировать переменную, используя встроенный код внутри самого основного тега, и это не сработало. я знаю, что файл был импортирован правильно, потому что кнопки работают нормально.
Ответ №1:
Похоже, вы хотите взять document.write и отобразить его на экране.
;
// Display that message by appending it to an HTML element
yourHTMLELEMENTWHEREYOUWANTITTODISPLAY.appendChild(msgDiv);
}
//call the function
myFunction()
//add an eventlistener on function
button.addEventListener('click', myFunction)
You have your quiz wrapped in a form, so you can just add an add event listener on that element. That way when the quiz is at the end and when someone hits submit the other function to display the results can run. Also you want to have the form submit so that they can either click or hit enter so submit.
form.addEventListener('submit' (e) => {
// this stops the page from submitting and going to another page
e.preventDefault();
// Add the code from up above.
// You don't want your check function to be in this code because it will only run when the form is submitted and you don't want that.
})
Комментарии:
1. как бы я вызвал эту функцию? я бы только создал эту функцию в файле js, а затем вызвал в html? я новичок в html и js, поэтому я пытаюсь понять, как все работает.
2. Обычно вы хотите разделить javascript и html. Вы могли бы получить доступ к javascript, имея файл сценария, расположенный в html-файле, например <script src=»main.js «></script>
3. И чтобы вызвать функцию it, вы бы назвали ее так myFunction() , Вы также можете добавить прослушиватель событий, чтобы он вызывался только тогда, когда кто-то выполняет действие, например, щелчок или наведение курсора мыши
4. @Yusuf Hanif Существует несколько способов добавления прослушивателя событий в функцию. Стоит взглянуть на документ javascript, чтобы помочь вам.
5. Единственная проблема с прослушивателем событий заключается в том, что мне посоветовали не использовать jquery. Не уверен, что jquery усложнит или упростит задачу, но я должен воздержаться от этого. Я также попытаюсь найти способ заставить его работать. Спасибо👍