2017-03-10 7 views
0

私はこのコードをDRYしようとしています。手作業でループしたい(または数字を増やす)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)); 
    } 
}) 
関連する問題