[英]how do i attach array value to current position
<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);
}
我想單擊單選按鈕而不是更改圖像。 圖像名稱存儲在數組中,它將通過addEventlistener函數附加到附件中,但是無效。
使用相同的HTML,您可以按以下方式修改腳本
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'));
});
這是一個工作中的JsFiddle
with循環,當您的點擊回調觸發時,變量提升,它將始終返回c中的最后一個元素。使用閉包將有所幫助。
for(var i = 0 ; i < b.length ; i++){
(function(){
var img = c[i];
b[i].addEventListener('click', function () {
a.src = img +'.jpg' ;
} ,false);
}())
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.