繁体   English   中英

我如何将数组值附加到当前位置

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM