jQuery - 在现有的 each() 事件中嵌套另一个 each() 循环不起作用

Posted

技术标签:

【中文标题】jQuery - 在现有的 each() 事件中嵌套另一个 each() 循环不起作用【英文标题】:jQuery - Nesting another each() loop inside existing each() event not working 【发布时间】:2020-02-11 18:53:52 【问题描述】:

我正在尝试从具有多个选项的 JSON 数据创建一个表,我在其中拆分数据并使用 .each() 循环遍历每个选项。

下面是我使用的 JSON 数据:

var StatJSON = 
        "Volvo": 
            "Options": "Option1-Black,car/Option2-Blue,car&bus"
        ,
        "Mercedes": 
            "Options": "Option1-Blue,car/Option2-Blue,car&bus"
        ,
    ;

我面临的挑战是我需要在每个“选项”中创建另一个循环,以使用“&”作为分隔符来选择每个“车辆类型”(即 JSON 中的汽车、公共汽车)。我用来循环数据的 jQuery 如下(针对下面的相关语句放置 cmets):

jQuery('.divResult table tbody tr td').each(function ($) 
    if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function () 
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) 
            var html = '<table class="InnerTable">';
            jQuery.each(Options, function(index, value)
                var OptionNumber = value.split('-')[0];
                var OptionData = value.split('-')[1];
                var OptionColor = OptionData.split(',')[0];
                var OptionTransport = OptionData.split(',')[1];
                var OptionTransportArray = OptionTransport.split('&'); // <-- Splitting the transport options

                for (i=0; i<OptionTransportArray.length; i++)
                  var OptionTransportEach = OptionTransport.split('&')[i]; // <-- Looping the options
                

                html += '<tr><td colspan="2">'+ OptionNumber +'</td></tr>'
                html += '<tr><td>Color:'+ OptionColor +'</td>'
                html += '<td><span class="fas fa-'+OptionTransportEach+'"></span></td></tr>' //  <-- Adding each option  
            );
            html += '</table>'
            return html;
        
        jQuery(this).empty().append(HowToReach(data));
    );
 );

不幸的是,它不会遍历两个元素,只显示数组中的第 n 个元素,即在“Option2”的情况下只显示“总线”而不是“汽车”。

我哪里出错了,如何更正我的代码以确保循环显示每个元素,并用“&”符号分隔。

下面是完整的工作代码:

jQuery(document).ready(function($) 

  var StatJSON = 
    "Volvo": 
      "Options": "Option1-Black,car/Option2-Blue,car&bus"
    ,
    "Mercedes": 
      "Options": "Option1-Blue,car/Option2-Blue,car&bus"
    ,
  ;

  jQuery('#btnSubmit').click(function() 
    var data = [];
    jQuery("#selection").find(':selected').each(function(e) 
      var this_input = jQuery(this);
      if (this_input.is(':selected')) 
        data.push(this_input.val());
      
    );

    $('#divResult').empty().append(PrintTable(data));

    jQuery('.divResult table tbody tr td').each(function($) 
      if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function() 
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) 
          var html = '<table class="InnerTable">';
          jQuery.each(Options, function(index, value) 
            var OptionNumber = value.split('-')[0];
            var OptionData = value.split('-')[1];
            var OptionColor = OptionData.split(',')[0];
            var OptionTransport = OptionData.split(',')[1];
            var OptionTransportArray = OptionTransport.split('&');

            for (i = 0; i < OptionTransportArray.length; i++) 
              var OptionTransportEach = OptionTransport.split('&')[i];
            

            html += '<tr><td colspan="2">' + OptionNumber + '</td></tr>'
            html += '<tr><td>Color:' + OptionColor + '</td>'
            html += '<td><span class="fas fa-' + OptionTransportEach + '"></span></td></tr>'
          );
          html += '</table>'
          return html;
        
        jQuery(this).empty().append(HowToReach(data));
      );
    );

    function PrintTable(data) 
      var html = '<table class="compTable"><thead><tr><th>';
      if (data && data.length) 
        html += '</th>';
        jQuery.each(data, function(k, v) 
          html += '<th id="myHeader" class="header2">' + v + '</th>';
        );
        html += '</tr>';
        html += '<tbody>';
        jQuery.each(StatJSON[data[0]], function(k, v) 
          html += '<tr><td>' + k + '</td>';
          jQuery.each(data, function(k2, v2) 
            html += '<td>' + StatJSON[data[k2]][k] + '</td>';
          );
          html += '</tr>';
        );
       else 
        html += 'No results found</td></tr>';
      
      html += '</tbody></table>';
      return html;
    


  );

);
body 
  font-family: montserratbold, montserratregular, sans-serif;


.divResult 
  overflow: scroll;
  position: relative;


.compTable 
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;


.InnerTable 
  margin: 1px;
  border: 1px solid #222;
  text-align: center;
<html>

<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src='https://kit.fontawesome.com/a076d05399.js'></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/brands.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/fontawesome.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/regular.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
</head>

<select id="selection" multiple="multiple">
  <option value="Volvo">Volvo</option>
  <option value="Mercedes">Mercedes</option>
  <br />
  <input id="btnSubmit" class="button" type="submit" value="submit" />
</select>
<br /><br />
<div id="divResult" class="divResult"></div>

【问题讨论】:

【参考方案1】:

您需要将循环向下移动并基于它构建 html

jQuery(document).ready(function($) 

  var StatJSON = 
    "Volvo": 
      "Options": "Option1-Black,car/Option2-Blue,car&bus"
    ,
    "Mercedes": 
      "Options": "Option1-Blue,car/Option2-Blue,car&bus"
    ,
  ;

  jQuery('#btnSubmit').click(function() 
    var data = [];
    jQuery("#selection").find(':selected').each(function(e) 
      var this_input = jQuery(this);
      if (this_input.is(':selected')) 
        data.push(this_input.val());
      
    );

    $('#divResult').empty().append(PrintTable(data));

    jQuery('.divResult table tbody tr td').each(function($) 
      if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function() 
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) 
          var html = '<table class="InnerTable">';
          jQuery.each(Options, function(index, value) 
            var OptionNumber = value.split('-')[0];
            var OptionData = value.split('-')[1];
            var OptionColor = OptionData.split(',')[0];
            var OptionTransport = OptionData.split(',')[1];
            var OptionTransportArray = OptionTransport.split('&');
            console.log(OptionTransportArray);
            

            html += '<tr><td colspan="2">' + OptionNumber + '</td></tr>'
            html += '<tr><td>Color:' + OptionColor + '</td>'
            html += '<td>'
            for (i = 0; i < OptionTransportArray.length; i++) 
              html+= '<span class="fas fa-' + OptionTransport.split('&')[i] + '"></span>'
              
            html+='</td></tr>';
          );
          html += '</table>'
          return html;
        
        jQuery(this).empty().append(HowToReach(data));
      );
    );

    function PrintTable(data) 
      var html = '<table class="compTable"><thead><tr><th>';
      if (data && data.length) 
        html += '</th>';
        jQuery.each(data, function(k, v) 
          html += '<th id="myHeader" class="header2">' + v + '</th>';
        );
        html += '</tr>';
        html += '<tbody>';
        jQuery.each(StatJSON[data[0]], function(k, v) 
          html += '<tr><td>' + k + '</td>';
          jQuery.each(data, function(k2, v2) 
            html += '<td>' + StatJSON[data[k2]][k] + '</td>';
          );
          html += '</tr>';
        );
       else 
        html += 'No results found</td></tr>';
      
      html += '</tbody></table>';
      return html;
    


  );

);
body 
  font-family: montserratbold, montserratregular, sans-serif;


.divResult 
  overflow: scroll;
  position: relative;


.compTable 
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;


.InnerTable 
  margin: 1px;
  border: 1px solid #222;
  text-align: center;
<html>

<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src='https://kit.fontawesome.com/a076d05399.js'></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/brands.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/fontawesome.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/regular.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
</head>

<select id="selection" multiple="multiple">
  <option value="Volvo">Volvo</option>
  <option value="Mercedes">Mercedes</option>
  <br />
  <input id="btnSubmit" class="button" type="submit" value="submit" />
</select>
<br /><br />
<div id="divResult" class="divResult"></div>

【讨论】:

以上是关于jQuery - 在现有的 each() 事件中嵌套另一个 each() 循环不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何在现有的 django 网站上开始使用 react

在 jQuery 中使用 bind() 和 each() 分配事件处理程序的区别?

jQuery常用事件,each循环,引用当前时间

jQuery事件,特殊属性操作,链式变成,each

jquery ajax添加元素事件无效,each,on函数参考

jQuery插件:返回此vs返回this.each()