在每个循环中访问它

时间:2015-10-16 20:54:40

标签: jquery twitter-bootstrap

为什么此代码仅适用于$(this)循环内的$.each,并且当我使用col参数时停止工作。这不是它应该如何工作?

$(document).ready(function() {
  var rows = $('div.row');
  $.each(rows, function() {
    var row = $(this);
    row.find('div.col-sm-6').each(function(index, col) {
      $(col).removeClass('col-sm-push-6');
      $(col).removeClass('col-sm-pull-6');
    });
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="row" style="display: block;">
  <div class="col-sm-6 col-sm-push-6">
    <br style="clear:both;">
    <div class="RIF_Csp2" id="yourCsp2" style="float:left;"><span class="RIF_Field RIF_State" id="yourState" style="display: none;"><label class="fldLbl" id="yourStateLabel">State:</label><br>
<span style="white-space: nowrap;"><select id="yourStateValue" name="yourState" onchange="null" onfocus="null" onblur="null" tabindex="0"><option value="">Select One</option></select><img alt="" height="9" id="yourStateReqdImg" src="/img/1.gif" width="11"></span></span>
    </div>
  </div>
  <div class="col-sm-6 col-sm-pull-6">
    <br style="clear:both;">
    <div class="RIF_Csp3" id="yourCsp3" style="float:left;"><span class="RIF_Field RIF_Postal" id="yourPostal" style="width: 200px;"><label class="fldLbl" id="yourPostalLabel">ZIP Code:</label><br>
<span style="white-space: nowrap;"><input id="yourPostalValue" maxlength="15" name="yourPostal" size="15" style="width:200px;" type="text" tabindex="0"><img alt="Required" height="9" id="yourPostalReqdImg" src="/img/icn_dia.gif" width="11"></span></span>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

简短回答

使用$(col),而不是col

答案很长

col参数与使用this相同。如果您要替换$(this),则应使用$(col)。像这样:

$(document).ready(function() {
  var rows = $('div.row');
  $.each(rows, function() {
    var row = $(this);
    row.find('div.col-sm-6').each(function(index, col) {
      $(col).removeClass('col-sm-push-6');
      $(col).removeClass('col-sm-pull-6');
    });
  });
});

.eachrow.find('div.col-sm-6')内循环的数组实际上是DOM元素的数组。所以,如果你想使用像.removeClass这样的jQuery方法,你应该用$()包装它。

答案 1 :(得分:1)

出于同样的原因,您使用$(this)代替this

$(col)是该元素的jQuery对象,就像使用this / $(this)一样。