<img src="img.jpg" id="try" width="200px" height="100px" alt="Loading">
<input type="radio" name="round" value=0 >
<input type="radio" name="round" value=1>
<input type="radio" name="round" value=2>
var a = document.getElementById('try') ;
var b = document.getElementsByName('round') ;
var c = ['trophy','check','Hello'] ;
for(var i = 0 ; i < b.length ; i++){
b[i].addEventListener('click', function () {
a.src = c[i]+'.jpg' ;
} ,false);
}
i want to click on radio button than change image . image name store in array this will attach by addEventlistener function through but it won't work .
With the same Html you can make modifications to your script as below
var c = ['trophy','check','Hello'] ;
$('input[name="round"]').on('click',function(){ // bind event to all radio buttons at once
$('#try').attr('src',c[$(this).attr('value')]+'.jpg'); //on click take the value of the radio button and then use it to get value from array and set as source to img
//alert($('#try').attr('src'));
});
Here is a Working JsFiddle
with loop, when your click callback fires,variable hoisting ,it will return always the last element in c.Using closure will be help..
for(var i = 0 ; i < b.length ; i++){
(function(){
var img = c[i];
b[i].addEventListener('click', function () {
a.src = img +'.jpg' ;
} ,false);
}())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.