#javascript #select
#javascript #выберите
Вопрос:
Я работаю над приложением для быстрой записи. В этом приложении я хочу включить возможность выбора разных списков слов.
Моя проблема в том, как я могу выбрать переменную для списка слов.
Именно так это работает без выбора списка слов:
window.addEventListener('load', init);
let messagegameover;
messagegameover = "<span style='color:#ff0000'>Game over!</span>"; // store the string
let messagecorrect;
messagecorrect = "<span style='color:green'>Correct!!</span>";
//**************
const select = document.getElementById("language-select");
const textSpan = document.getElementById("text-span");
const valueSpan = document.getElementById("value-span");
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
// Show on page load
showTextAndValue(select, textSpan, valueSpan);
// Hook the `input` event
select.addEventListener("input", () => {
// Update the contents of the elements
showTextAndValue(select, textSpan, valueSpan);
});
//**********************
// Schwierigkeitsgrad
const levels = {
easy: 5,
medium: 3,
hard: 2
}
// Auswahl des Schwierigkeitsgrads
const currentLevel = levels.easy;
// Globale Variablen
let time = currentLevel;
let score = 0;
let isPlaying;
// DOM-Elemente
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');
const wordsdeu = [
'Hund', 'Katze', 'Maus'
];
const wordseng = [
'dog', 'cat', 'mouse'
];
// Spielstart
function init() {
// Zahl in Sekunden anzeigen
seconds.innerHTML = currentLevel;
// Lade Wörter aus Array
showWord(wordseng); //replace wordseng by valueSpan
// Worteingabe prüfen
wordInput.addEventListener('input', startMatch);
// Countdown Sekunden
setInterval(countdown, 1000);
// Spielstatus
setInterval(checkStatus, 50);
}
// Wortgleichzeit prüfen
function startMatch() {
if (matchWords()) {
isPlaying = true;
time = currentLevel 1;
showWord(wordseng); //replace wordseng by valueSpan
wordInput.value = '';
score ;
}
// wenn score <0, dann 0
if (score === -1) {
scoreDisplay.innerHTML = 0;
} else {
scoreDisplay.innerHTML = score;
}
}
// prüfen ob Wörter gleich
function matchWords() {
if (wordInput.value === currentWord.innerHTML) {
message.innerHTML = messagecorrect;
return true;
} else {
message.innerHTML = ' ';
return false;
}
}
// zufällige Wortanzeige
function showWord(wordseng) { //replace wordseng by valueSpan
// zufälliges Array für Index
const randIndex = Math.floor(Math.random() * wordseng.length); //replace wordseng by valueSpan
// zufälliges Wort
currentWord.innerHTML = wordseng[randIndex]; //replace wordseng by valueSpan
}
// timer
function countdown() {
// prüfen, ob Zeit abgelaufen
if (time > 0) {
// abnehmend
time--;
} else if (time === 0) {
// Spielende
isPlaying = false;
}
// Restzeit
timeDisplay.innerHTML = time;
}
function checkStatus() {
if (!isPlaying amp;amp; time === 0) {
//message.innerHTML = 'Game Over!!!';
message.innerHTML = messagegameover;
score = -1;
}
}
<label for="language">Choose a language:</label>
<select name="language" id="language-select" value="wordsdeu">
<option value="wordseng">English</option>
<option value="wordsdeu">Deutsch</option>
</select>
<p>The following two lines are for testing purposes only</p>
<p>You selected: <span id="text-span"></span></p>
<p>You selected the following option: <span id="value-span"></span></p>
<!-- strange behaviour: does not work if I remove the line before -->
<br><br>
<p class="maxtimetext">Max. time to write this word:
<span class="maxtime" id="seconds"></span> Seconds</p>
<br>
<h2 id="current-word">hello</h2>
<input type="text" spellcheck="false" placeholder="Start typing..." id="word-input" autofocus>
<h4 class="message" id="message"></h4>
<br>
<h3>Time Left: <span class="time-left" id="time">0</span></h3>
<br>
<p class="score">Score: <span id="score">0</span></p>
<br>
<p>Game over? To restart just type the word!</p>
<script src="./script.js"></script>
Следующий фрагмент показывает мой желаемый код, который, по-видимому, неисправен:
window.addEventListener('load', init);
let messagegameover;
messagegameover = "<span style='color:#ff0000'>Game over!</span>"; // store the string
let messagecorrect;
messagecorrect = "<span style='color:green'>Correct!!</span>";
//**************
const select = document.getElementById("language-select");
const textSpan = document.getElementById("text-span");
const valueSpan = document.getElementById("value-span");
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
// Show on page load
showTextAndValue(select, textSpan, valueSpan);
// Hook the `input` event
select.addEventListener("input", () => {
// Update the contents of the elements
showTextAndValue(select, textSpan, valueSpan);
});
//**********************
// Schwierigkeitsgrad
const levels = {
easy: 5,
medium: 3,
hard: 2
}
// Auswahl des Schwierigkeitsgrads
const currentLevel = levels.easy;
// Globale Variablen
let time = currentLevel;
let score = 0;
let isPlaying;
// DOM-Elemente
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');
const wordsdeu = [
'Hund', 'Katze', 'Maus'
];
const wordseng = [
'dog', 'cat', 'mouse'
];
// Spielstart
function init() {
// Zahl in Sekunden anzeigen
seconds.innerHTML = currentLevel;
// Lade Wörter aus Array
showWord(valueSpan); //replace wordseng by valueSpan
// Worteingabe prüfen
wordInput.addEventListener('input', startMatch);
// Countdown Sekunden
setInterval(countdown, 1000);
// Spielstatus
setInterval(checkStatus, 50);
}
// Wortgleichzeit prüfen
function startMatch() {
if (matchWords()) {
isPlaying = true;
time = currentLevel 1;
showWord(valueSpan); //replace wordseng by valueSpan
wordInput.value = '';
score ;
}
// wenn score <0, dann 0
if (score === -1) {
scoreDisplay.innerHTML = 0;
} else {
scoreDisplay.innerHTML = score;
}
}
// prüfen ob Wörter gleich
function matchWords() {
if (wordInput.value === currentWord.innerHTML) {
message.innerHTML = messagecorrect;
return true;
} else {
message.innerHTML = ' ';
return false;
}
}
// zufällige Wortanzeige
function showWord(valueSpan) { //replace wordseng by valueSpan
// zufälliges Array für Index
const randIndex = Math.floor(Math.random() * valueSpan.length); //replace wordseng by valueSpan
// zufälliges Wort
currentWord.innerHTML = valueSpan[randIndex]; //replace wordseng by valueSpan
}
// timer
function countdown() {
// prüfen, ob Zeit abgelaufen
if (time > 0) {
// abnehmend
time--;
} else if (time === 0) {
// Spielende
isPlaying = false;
}
// Restzeit
timeDisplay.innerHTML = time;
}
function checkStatus() {
if (!isPlaying amp;amp; time === 0) {
//message.innerHTML = 'Game Over!!!';
message.innerHTML = messagegameover;
score = -1;
}
}
<label for="language">Choose a language:</label>
<select name="language" id="language-select" value="wordsdeu">
<option value="wordseng">English</option>
<option value="wordsdeu">Deutsch</option>
</select>
<p>The following two lines are for testing purposes only</p>
<p>You selected: <span id="text-span"></span></p>
<p>You selected the following option: <span id="value-span"></span></p>
<!-- strange behaviour: does not work if I remove the line before -->
<br><br>
<p class="maxtimetext">Max. time to write this word:
<span class="maxtime" id="seconds"></span> Seconds</p>
<br>
<h2 id="current-word">hello</h2>
<input type="text" spellcheck="false" placeholder="Start typing..." id="word-input" autofocus>
<h4 class="message" id="message"></h4>
<br>
<h3>Time Left: <span class="time-left" id="time">0</span></h3>
<br>
<p class="score">Score: <span id="score">0</span></p>
<br>
<p>Game over? To restart just type the word!</p>
<script src="./script.js"></script>
Что я также заметил и, возможно, связано с проблемой, так это то, что если в следующем коде я удаляю первую строку, она не отображает и вторую строку, чего я не понимаю:
<p>You selected: <span id="text-span"></span></p>
<p>You selected the following option: <span id="value-span"></span></p> <!-- strange behaviour: does not work if I remove the line before -->
Я поместил его в JSFiddle для тестирования:
https://jsfiddle.net/engr58wm /
Комментарии:
1. Вместо двух отдельных переменных
wordsdeu
иwordseng
используйте объект , который имеет два свойства по этим именам, и фактические массивы данных, хранящиеся под ними. Затем вы можете легко получить доступ к правильному списку на основе выбранного вами значения параметра черезobjectVarName[selectedOptionValue]
2.Для меня это имеет смысл. Итак, я изменил переменную на
const words = { wordsdeu: ['Hund','Katze','Maus'], wordseng: ['dog','cat','mouse'] }
, но я не знаю, как ее решить. На самом деле, я думаю, не хватает моего знания синтаксиса. Я только что создал новую скрипку: jsfiddle.net/msori58/engr58wmfunction showWord(words[valueSpan) {
илиcurrentWord.innerHTML = words[valueSpan][randIndex];
они определенно ошибочны, но каков правильный синтаксис?3. Вы получаете к ним доступ через
words.wordsdeu
andwords.wordseng
, который в JavaScript также может быть записан какwords["wordsdeu"]
andwords["wordseng"]
. И поскольку в последнем синтаксисе имена этих свойств теперь выражаются через текстовые литералы, вы также можете заменить эти литералы переменной , содержащей то же строковое значение.var whatToAccess = "wordsdeu"; do_something_with( words[whatToAccess] );
4.
function showWord(words[valueSpan])
неверно. Это определение функции, поэтому вам нужно использовать имя параметра, которое соответствует соглашениям для таких идентификаторов в JavaScript. Вы можете передать значение, например,words[valueSpan]
при вызове функции, но в этом месте это просто не имеет никакого смысла.5. Хорошо, исправил это. По-прежнему не работает. Может быть, по той же причине, почему он не показывает значение valueSpan, когда я опускаю
const textSpan = document.getElementById("text-span");
сверху? См . jsfiddle.net/engr58wm Например , правильно ли этоcurrentWord.innerHTML = words[valueSpan][randIndex];
? Выглядит странно для меня, но я не знаю, в чем ошибка. Я совершенно уверен, что в моем коде не хватает только крошечной вещи.