简体   繁体   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); 
   }  

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 . 图像名称存储在数组中,它将通过addEventlistener函数附加到附件中,但是无效。

With the same Html you can make modifications to your script as below 使用相同的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'));
 });

Here is a Working JsFiddle 这是一个工作中的JsFiddle

with loop, when your click callback fires,variable hoisting ,it will return always the last element in c.Using closure will be help.. 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.

相关问题 聚合物 - 如何将观察者附加到数组? - Polymer - How do I attach an observer to an array? 如何将事件处理程序附加到当前事件? - How do I attach event handler to current event? 如何将useState变量中的当前值存储在数组中? - How do I store the current value from a useState variable in an array? 如何将图片附加到数组的位置? javascript - how to attach a picture to the position of an array? javascript 如何将链接附加到单个数组项目? - How do I attach links to individual array items? 如何在数组的开头和结尾附加项目? - How do I attach an item at the beginning and at the end of an Array? Javascript:如何将单个元素的值从数组复制到同一位置的另一个数组中? - Javascript: how do I copy the value of a single element from an array into another array at the same position? 如何获取从数组调用的按钮的当前值,以显示另一个数组的内容? - How do I get the current value of a button being called from an array to display something from another array? 如何从javascript数组中获取下一个值以与for循环中的当前值进行比较 - How do I get the next value from a javascript array to compare against the current value in a for loop 如何使此功能更新当前鼠标位置? - How do I make this function update the current mouse position?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM