2015-10-16 110 views
0

爲什麼此代碼僅適用於$.each循環內的$(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'); 
 
    }); 
 
    }); 
 
});
<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>

+0

你使用'col'還是'$(col)'? – Diego

回答

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

陣列裏面row.find('div.col-sm-6').each環路實際上是DOM元素的數組。所以,如果你想使用像.removeClass這樣的jQuery方法,你應該用$()來包裝它。

1

出於同樣的原因,您使用$(this)而不是this

$(col)是該元素的jQuery對象,就像this/$(this)一樣。