【问题标题】:Break one row with jQuery each [Bootstrap | JSON]每个用 jQuery 打破一行 [Bootstrap | JSON]
【发布时间】:2015-10-02 08:38:52
【问题描述】:

我是 jQuery 的新手,最近有个问题困扰着我。

我正在使用 jQuery + Bootstrap + JSON 创建一个页面,并在 Bootstrap Grid 中输出结果。我不知道如何描述它,但我会尝试用代码编写它。

这是我想要实现的输出。

<div id = "appendClasses">
<div class = "row">
<div class = "col-md-4"><p>Party 1</p></div>
<div class = "col-md-4"><p>Party 2</p></div>
<div class = "col-md-4"><p>Party 3</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 4</p></div>
<div class = "col-md-4"><p>Party 5</p></div>
<div class = "col-md-4"><p>Party 6</p></div>
</div>
</div>

名单还在继续。

我有这样的 HTML。

<div id = "appendClasses"></div>

以及 jQuery 生成 HTML 并将其注入 #appendClasses

$.getJSON(partyURL, function(partyURLResponse) {
    var partyHTML = '';
$.each(partyURLResponse.data, function(partyIdx, party) {
        /*optional stuff to do after success */
       partyHTML += '<div class = "row">';
       partyHTML += '<div class = "col-md-4">';
       partyHTML += '<p>' + party.id + '</p>';
       partyHTML += '</div>';
       partyHTML += '</div>';
        partyHTML += '</div>';
    });
    $('#appendClasses').html(partyHTML);
  });

这是它的输出方式。

<div id = "appendClasses">
<div class = "row">
<div class = "col-md-4"><p>Party 1</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 2</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 3</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 4</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 5</p></div>
</div>
<div class = "row">
<div class = "col-md-4"><p>Party 6</p></div>
</div>
</div>

所以它在没有网格的情况下以一行显示结果。我该如何解决这个问题?

【问题讨论】:

  • 做个柜台怎么样?
  • 尝试使用 if 循环。它没有显示我想要的结果。
  • 我做到了。我把 if 换成一行(在你提到的 class= "row" 之后),但结果仍然相同。
  • 我认为在这种情况下你需要一个嵌套循环。
  • 你能演示一下吗?我还在为此苦苦挣扎。

标签: javascript jquery html json twitter-bootstrap


【解决方案1】:

在您当前的代码中,您添加&lt;div class='row'&gt; 到每一方,您可以通过仔细计算当前id 来解决它,并且:

  1. 当当前索引位于行首时,执行partyHTML += '&lt;div class = "row"&gt;';
  2. 当行项目已满或循环以非空行结束时,执行partyHTML += '&lt;/div&gt;'; 将其关闭。

例如:

var count = 0;
var item_per_row = 3;
$.each(partyURLResponse.data, function(partyIdx, party) {
   /*optional stuff to do after success */
   if (count === 0) { // Start of a row
    partyHTML += '<div class = "row">';
   }
   partyHTML += '<div class = "col-md-4">';
   partyHTML += '<p>' + party.id + '</p>';
   partyHTML += '</div>';

   ++count;
   if (count === item_per_row) {  // End of row
    partyHTML += '</div>';
   }

   // It seems you mistakenly closed one more div in loop
   // is it a typo?
   // partyHTML += '</div>';
});
if (count > 0) {  // Close the last row if it exist.
  partyHTML += '</div>';
}

$('#appendClasses').html(partyHTML);

但是,当您使用纯文本来管理代码时,很难维护(因为您似乎在每次迭代中添加了一个额外的 &lt;/div&gt;),因为您使用的是 jQuery,我建议您使用它用于管理 dom 元素及其属性...等的 api,这将更容易维护和做未来的更改。

var parties = [
  {id: 1},
  {id: 2},
  {id: 3},
  {id: 4},
  {id: 5}
];
// Items per row.
var items_per_row = 3;
// current item counts in a row.
var item_count = 0;

// Create a row to place the created divs
var $row = $('<div>').addClass('row');

// Get target to place these items.
var $target = $('#appendClasses');
$.each(parties, function(partyIdx, party) {
  /*optional stuff to do after success */
  // Just use jquery's function to create the dom elements would be more clear.
  
  var div = $('<div>');            // Create div.
  
  var p = $('<p>').text(party.id);  // Create p and add text to it.
  div
    .addClass('col-md-4')     // add class `col-md-4` to div
    .append(p)                         // append the p to the div
    .appendTo($row);           // append the div to the row.
  
  ++item_count;
  
  // When item count reach limit, append row to target
  // and create a new row for later elements.
  if (item_count === items_per_row) {    
    $row.appendTo($target);
    $row = $('<div>').addClass('row');
    item_count = 0;
  }
});

if (item_count > 0) {
  $row.appendTo($target);
}
.row {
  margin-bottom: 10px;
  border: solid 1px blue;
  padding: 10px;
  width : 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "appendClasses"></div>

【讨论】:

    【解决方案2】:

    你可以在每个身体中使用彼此,当 json 结构会像这里一样 - 我的快速plunker 代码。 并且您可以从服务器数组返回,然后按照您的需要解析和渲染它会很好。

    [
      [{id: 1}, {id: 2}, {id: 3}],
      [{id: 4}, {id: 5}, {id: 6}]
    ]
    

    然后这段代码就会很好用:

    $.each(partyURLResponse.data, function(partyIdx, party) {
        /*optional stuff to do after success */
        partyHTML += '<div class = "row">';
    
        $.each(party, function(id, item) {
          partyHTML += '<div class = "col-md-4">';
          partyHTML += '<p>' + item.id + '</p>';
          partyHTML += '</div>';
        });
    
        partyHTML += '</div>';
      });
    
      $('#appendClasses').append(partyHTML);
    });
    

    【讨论】:

      【解决方案3】:

      这是另一种代码最少的方法。我留下了内联 cmets 来表示每一行的作用。

      var parties = [{id: 'p1'},{id: 'p2'},{id: 'p3'},{id: 'p4'},{id: 'p5'},{id: 'p6'}],
      	//Create empty containers for later use
      	$html = $rows = $(),
      	//Break limit
          colsPerWrap = 3;
      
      $.each(parties, function(partyIdx, party) {
      	//Create a jQuery object with the desired content
          var $col = $("<div/>", {
              'class': 'col-md-4',
              'html': '<p>' + party.id + '</p>'
          });
      	//Add the created object to the container
          $rows = $rows.add($col);
      	//At every break limit
          if ( (partyIdx+1) % colsPerWrap === 0 ) {
      	    //Append the cols to the inner wrapper
              var $wrap = $("<div/>", { 'class': 'row' });
              $wrap.append($rows);
      	    //Empty the container for the next iteration
              $rows = $();
      	    //Populate the container with each inner wrapper
              $html = $html.add($wrap);
          }
      });
      //Always append outside the loop as DOM scan is expensive!
      $('#appendClasses').empty().append($html);
      .row {
          border: 1px solid green;
          margin-bottom: 20px;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id = "appendClasses"></div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-06
        • 2010-12-19
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多