#javascript #html #arrays #onclick #setinterval
#javascript #HTML #массивы #onclick #setinterval
Вопрос:
Я написал на HTML и Javascript веб-страницу, которая циклически перебирает изображения льва и лягушки. Я установил 2 кнопки для запуска и остановки циклирования изображений каждые 500 мс. Моя проблема в том, что я не уверен, как обойти создание функции оценки, которая подсчитывает количество нажатий на определенное изображение. Например, если щелкнуть изображение лягушки, я хочу, чтобы оценка была равна 1, а если щелкнуть изображение льва, я хочу, чтобы оценка была равна -1. Вот мой код.
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
Ответ №1:
замените вашу функцию scoreNumb на мою
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/* 1*/
valueScore ;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
Комментарии:
1. @zerbene да, правильно. его всегда идеально использовать
textContent
(там, где заменяется только текст). Вы можете прочитать больше о недостатках innerHTML в MDN здесь, вSecurity considerations
разделе
Ответ №2:
Вы почти на месте. Вам просто нужно проверить, какое изображение было clicked
checking
в img src
Если изображение src
есть lion
, вы можете увеличить переменную totalScore
count, обновив count
ее также с помощью textContent
метода.
function scoreNumb(e) {
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore
} else {
totalScore--
}
score.textContent = totalScore
}
Рабочая демонстрация:
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/200"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
var totalScore = 0
function start() {
imgInterval = setInterval(displayImage, 1000); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop() {
clearInterval(imgInterval);
}
function scoreNumb(e) { //This is where i think i am having issues and am unsure what to do.
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore
} else {
totalScore--
}
score.textContent = totalScore
}
<html>
<head>
<title>Question 2</title>
<script>
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br /> <br />
<span>
<img id="image" onclick=scoreNumb(this) width="250px" />
</span>
<br />
<span id="score">0</span>
</body>
</html>
Комментарии:
1. Я чувствую, что это слишком сложно для того, о чем я спрашиваю, но, тем не менее, работает, спасибо!
2. @TurkeyDurkey я мог
index
бы также использовать изображение. но я чувствовал, что это идеально, если вы специально хотите создатьlion
идею илиfrog
с помощью src, если у вас много изображений — рад, что все это работает сейчас. Дайте мне знать, пожалуйста, если я смогу еще чем-нибудь помочь, приятель 🙂3. будет сделано, я постараюсь оставаться на связи!
Ответ №3:
Измените объявление этой переменной с:
let score = document.getElementById('score');
к этому:
let score = 0;
затем в функции с именем scoreNumb() измените следующее :
if (imgi.onclick == 0) {
score 1;
}
к этому :
if (imgi === 0) {
score = 1;
}
else{
score -= 1;
}
// Here you can update your html code with getElementById.
console.log(score)