【问题标题】:Javascript loop through array inside an eventJavascript循环遍历事件内的数组
【发布时间】:2017-03-10 03:43:48
【问题描述】:

我正在尝试干掉这段代码,而不是在我想要循环的 if/else 语句中手动输入 elems 选项(或增加数字)。我尝试过使用各种循环,但无法让它在 .change() 事件中工作。

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">

【问题讨论】:

    标签: javascript jquery arrays loops


    【解决方案1】:

    您可以将if/else 替换为for 循环,如下所示:

    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;
            } 
        }
    });
    

    【讨论】:

      【解决方案2】:
      elems.forEach(function(elem){
        if (linkName === elem) {
         $("#response" + elem.substring(1)).html(localStorage.getItem(linkName));
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2018-12-18
        • 1970-01-01
        • 2013-08-16
        • 1970-01-01
        • 1970-01-01
        • 2017-12-12
        • 2015-10-15
        • 2015-11-08
        相关资源
        最近更新 更多