2016-06-09 3 views
0

Мне не удавалось использовать переменные javascript в html. В нижней части кода я хотел показать изображения с динамическими путями. Но это не работает. Когда я пишу, я искал, но ответы не были моим излечением. Заранее спасибо.Использование переменных javascript в html

<a href="#"><script type="text/javascript"> 
document.write('<img src="./images/bird.gif" name="img0" id="img0" onclick="javascript:fnChangeBorder(0);return false;"></a>')</script> 

он работает, но не тогда, когда я пишу

<a href="#"><script type="text/javascript"> 
document.write('<img src="'+imagelink0+'" name="img0" id="img0" onclick="javascript:fnChangeBorder(0);return false;"></a>')</script> 

Я не силен в JavaScript. Так что вы можете быть немного проще, объясняя. Вот весь код:

<!DOCTYPE html> 
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 


<body> 
<style> 
.greenClass { 
    border: 3px solid #FFCC66; 
    filter: opacity(30%); 
} 
.redClass { 
    border: 3px solid #FF0000; 
    filter:opacity(30%); 
} 

</style> 

<!-- What I want to do is play random animal sound and show random 4 animal images. 
The user listens the animal sound and then chooses the correct animal image. 
If the user clicks the correct image then the border of the image changes to green otherwise to red. 
"sample3.mp3" has animal sounds in every 2 seconds. 0-2 seconds has bee sound, 2-4 seconds has dog sound, 4-6 seconds has cat sound .... 
imgarr array has animal names the same order with imgSounds. 
The problem that when I directly write the image path below, it works but when I write a dynamic path like in the next image below the images are not there. 


--> 

<audio id="sample" preload controls> 
    <source src="sample3.mp3" type="audio/mpeg" /> 
    Sorry 
</audio> 
<button onclick="myFunction()">Click me</button> 


<script> 
var audio = document.getElementById('sample'); 
var segmentEnd; 
var imgSounds = [0,2,4,6,8,10]; // Every sound has 2 seconds length (bee sound, dog sound, cat sound ...). In every 2 seconds a different sound starts. All in one mp3 file. 
var imgarr = ["bee","dog","cat","donkey","lion","bird"]; // image names are stored in an array. 
var shuffledSounds; 
var imagelink0; // This is variable keeps the dynamic link path > document.write('<img src="'+imagelink0+'" name="img0" id="img0" onclick="javascript:fnChangeBorder(0);return false;"></a>') 
var imagelink1; 
var imagelink2; 
var imagelink3; 

function myFunction() { 
audio.addEventListener('timeupdate', function(){ 
    if (segmentEnd && audio.currentTime.toFixed() >= segmentEnd) { 
     audio.pause(); 
    } 
}, false); 

var shuffledSounds = imgSounds.slice(); 
shuffle(shuffledSounds); 
imagelink0= "./images/"+imgarr[0]+".gif"; 
imagelink1= "./images/"+imgarr[1]+".gif"; 
imagelink2= "./images/"+imgarr[2]+".gif"; 
imagelink3= "./images/"+imgarr[3]+".gif"; 

// when shuffled the first item in the array has the random animal sound. 
// I mean that if shuffledSounds[0] is 4 then audio player goes to 4. second and plays the animal sound. 
playSegment(shuffledSounds[0]); 

function playSegment(startTime){ 
    segmentEnd = startTime+2; 
    audio.currentTime = startTime; 
    audio.play(); 
} 
} 




function shuffle(mixArray) { 
    var currentIndex = mixArray.length, temporaryValue, randomIndex; 
    while (0 !== currentIndex) { 
    randomIndex = Math.floor(Math.random() * currentIndex); 
    currentIndex -= 1; 
    temporaryValue = mixArray[currentIndex]; 
    mixArray[currentIndex] = mixArray[randomIndex]; 
    mixArray[randomIndex] = temporaryValue; 
    } 
    return mixArray; 
} 



function fnChangeBorder(imgID){ // Change border if correct image is clicked 
if (imgID == 0) { 
document.getElementById("img0").className = "greenClass"; 
} else { 
document.getElementById("img1").className = "redClass"; 
document.getElementById("img2").className = "redClass"; 
document.getElementById("img3").className = "redClass"; 
} 

} 

</script> 

<!--The problem is here. When I directly write the image path below, it works but when I write a dynamic path, the images are not there. 
one more thing: how can i show randomly 4 images one of which is the correct one. 
--> 

<a href="#"><script type="text/javascript"> 
document.write('<img src="'+imagelink0+'" name="img0" id="img0" onclick="javascript:fnChangeBorder(0);return false;"></a>')</script> 
<a href="#"><script type="text/javascript"> 
document.write('<img src="'+imagelink1+'" name="img1" id="img1" onclick="javascript:fnChangeBorder(1);return false;"></a>')</script> 
<a href="#"><script type="text/javascript"> 
document.write('<img src="'+imagelink2+'" name="img2" id="img2" onclick="javascript:fnChangeBorder(2);return false;"></a>')</script> 
<a href="#"><script type="text/javascript"> 
document.write('<img src="'+imagelink3+'" name="img3" id="img3" onclick="javascript:fnChangeBorder(3);return false;"></a>')</script> 

</body></html> 
+0

Вы бы лучше размещение 4 HTML теги изображений с идентификаторами внизу вашего html, а затем доступ к ним по идентификатору из одного и того же файла javascript. В настоящее время ваши переменные ('imagelink0' и т. Д.) Существуют в другой области, где вы пишете теги изображений. – James

ответ

0

Ключ к вашей проблеме заключается в том, что переменные установлены в их значение и когда они используются. Скорее всего, этот порядок неправильный. Простым решением было бы разместить код JavaScript, который устанавливает переменные выше линий document.write. Однако это решает только часть проблемы: изображения не будут меняться, если вы измените свои переменные.

Для этого вам необходимо изменить атрибут src ваших <img> тегов каждый раз, когда одна из ваших переменных изменит их значение.

Таким образом, вместо того, чтобы использовать document.write() вы должны поместить статический <img> тег в HTML код, дать ему атрибут id и доступ к нему с помощью JavaScript так:

var img = document.getElementById("#img-id"); 
function changeImgPath(newPath) { 
    img.src = newPath; 
} 
+0

Вы имеете в виду: var img = document.getElementById (" img0 "); функция changeImgPath (newPath) { img.src = newPath; } changeImgPath ("./ images/bird.gif"); Mutlak

+0

Да, что-то в этом роде. Только то, что вам нужно разместить html в html-части и javascript где-нибудь еще (между '