2017-03-10 43 views
0

我想干这个代码,具体而言,而不是手动输入我想要循环(或增加数字)的if/else语句中的elems选项。我试过使用各种循环,但不能让它在.change()事件中工作。Javascript循环通过数组内部的事件

var radioSelect = $("input[type='radio']"); 
var elems = ["q1","q2","q3","q4","q5","q6"]; 

radioSelect.change(function() { 

    // grab the name and value selected radio 
    // set localstorage 
    var linkName = $(this).attr('name'); 
    var value = $(this).val(); 
    localStorage.setItem(linkName, value); 

    // I am trying to loop/increment both through the elements 
    // and also through the #response[x] divs. 
    if (link_name === elems[1]) 
    { 
     $("#response1").html(localStorage.getItem(linkName)); 
    } 
    else if (link_name === elems[2]) 
    { 
     $("#response2").html(localStorage.getItem(linkName)); 
    } 
    else if (link_name === elems[3]) { 
     $("#response3").html(localStorage.getItem(linkName)); 
    } 
}); 

基本HTML

<input type="radio" name="q2" value="Yes"> 
<input type="radio" name="q2" value="No"> 

回答

1

您可以通过for循环如下替换if/else

var radioSelect = $("input[type='radio']"); 
var elems = ["q1","q2","q3","q4","q5","q6"]; 

radioSelect.change(function() { 

    // grab the name and value selected radio 
    // set localstorage 
    var linkName = $(this).attr('name'); 
    var value = $(this).val(); 
    localStorage.setItem(linkName, value); 

    // I am trying to loop/increment both through the elements 
    // and also through the #response[x] divs. 
    for(var i=1; i<=elem.length; i++){ 
     if (link_name === elems[i]){ 
      $("#response"+i).html(localStorage.getItem(linkName)); 
      break; 
     } 
    } 
}); 
0
elems.forEach(function(elem){ 
    if (linkName === elem) { 
    $("#response" + elem.substring(1)).html(localStorage.getItem(linkName)); 
    } 
})