How to select an element?
Why this code does not work? And is there another way to select the first item?
<div>
<a href="#">text</a>
<a href="#">text</a>
</div>
<script type="text/javascript">
$(function() {
$('div a').each(function(){
$(':first', this).css(开发者_如何学C'color', 'red');
//...other actions with $(this)
});
});
</script>
I know that i can select an element like this: $('div a:first')
These will work.
$('div a').first();
$('div a').eq(0);
$('div a').slice(0,1);
$('div a').filter(':first');
If you only want the first, no sense looping.
If you will need the rest of them for some purpose, cache the result of the selector, the pull the one(s) you need.
var $div_a = $('div a');
$div_a.first(); // for the first
$div_a.slice(1,4); // for the second through fourth
Maybe this is what you want
<div>
<a href="#">text</a>
<a href="#">text</a>
</div>
<script type="text/javascript">
$(function() {
$('div a').each(function(i, elm){
if (i == 0){
$(elm).css('color', 'red');
}
//...other actions with $(this)
});
});
</script>
Inside an each loop, $(this) is the object you're looking for. You don't need to do any further selection unless you're searching for something inside of $(this). If you're trying to highlight the first, you should do it outside a call to each because it doesn't make much sense calling it n times.
$(function() {
$('div a').each(function(index){
if(index === 0){
$(this).css('color', 'red');
}
//...other actions with $(this)
});
});
精彩评论