我只需要將CSS樣式應用於符合我的標準的特定類。用一個簡單的數組我可以做到這一點:jQuery有條件
var ins = document.getElementsByClassName('ins');
for(var i = 0; i < ins.length; i++) {
if(ins.item(i).attributes[0].value == "ins right" || ins.item(i).attributes[0].value == "ins left")
ins[i].style.width = "120px"; //applies the width to left and right only
}
什麼是使用jQuery時的等價物? (可惜這寬度適用於所有三種元素)
if($('.ins').is('.left, .right'))
$('.ins').css('width','120px');
標記:
<div id="wrapper">
<div id="outer">
<div class="ins right">
<p>This is heading 3</p>
</div>
<div class="ins left">
<p>This is heading 1</p>
</div>
<div class="ins center">
<p>This is heading 2 This is heading 2 This is heading 2 This is heading 2 This is heading 2 This is heading 2 This is heading 2 This is heading 2</p>
</div>
</div>
</div>
作爲說明,您可以使用jQuery的hasClass對類進行條件檢查。 'if($('element')。hasClass('left')){...}'http://api.jquery.com/hasClass/ – mrtsherman 2012-01-30 15:55:24