[英]Run each() but only apply on the first result
How do I turn the first p to red? 如何将第一个p变成红色?
I'm using each()
because I need to search for all the P's. 我正在使用
each()
因为我需要搜索所有的P。 But I only want the code to work on the first result only, "exit" after that or something like that. 但是我只希望代码仅对第一个结果起作用,之后或类似的情况下“退出”。
How can I do that with jQuery? 我该如何使用jQuery?
PS: This is a simple example, the code is more complex than that, so please don't suggest something like $('p').eq(0)
or a CSS way... I need to do this with jQuery running the each method. PS:这是一个简单的示例,代码比这更复杂,所以请不要建议
$('p').eq(0)
或CSS方式...我需要在jQuery运行时执行此操作每种方法。
Thanks. 谢谢。
http://jsfiddle.net/ybr2qh46/ http://jsfiddle.net/ybr2qh46/
<p>name 1</p>
<p>name 2</p>
<p>name 3</p>
(function($){
$('p').each( function(){
$(this).css( 'color', 'red');
});
})(jQuery)
You can return false
in order to stop the loop from continuing to the next element: 您可以
return false
,以阻止循环继续到下一个元素:
(function($){ $('p').each( function(){ $(this).css( 'color', 'red'); return false; }); })(jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p>
Another option - if you want the loop to continue (but still want to change only the first element) - you can check if that element is the first one: 另一个选择-如果您希望循环继续(但仍只希望更改第一个元素)-您可以检查该元素是否是第一个:
(function($){ $('p').each( function(i) { if (i == 0) { $(this).css( 'color', 'red'); } }); })(jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p>
You can try to use .first()
method. 您可以尝试使用
.first()
方法。 It's used to select first selector if there is 1 or more than 1 selectors. 如果有一个或多个选择器,则用于选择第一个选择器。
$('p').first().css( 'color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p>
Another option ( must use each method ): 另一个选项( 必须使用每种方法 ):
var item = Array.from($('p').each(function (){}))[0]; $(item).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>name 1</p> <p>name 2</p> <p>name 3</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.