问题描述
在jQuery中,为什么只有eq()
既是选择器(:)又是方法(.),而不是gt()
和lt()
只是选择器(对象不支持该属性或方法")?
In jQuery, why only eq()
is both a selector (:) and a method (.), instead gt()
and lt()
are only selectors ("Object doesn't support that property or method")?
我不理解这种jQuery语法不一致/差异的特殊原因吗?
Is there a particular reason for this inconsistency/gap of jQuery syntax, that I do not understand?
$("#eq").click(function(){
alert($("li").eq(0).text());
$("li").eq(1).css("background-color", "yellow");
});
$("#eq2").click(function(){
alert($("li:eq(0)").text());
$("li:eq(1)").css("background-color", "yellow");
});
$("#gt").click(function(){
$("li").gt(1).css("background-color", "yellow");
});
$("#gt2").click(function(){
$("li:gt(1)").css("background-color", "yellow");
});
$("#lt").click(function(){
$("li").lt(1).css("background-color", "yellow");
});
$("#lt2").click(function(){
$("li:lt(1)").css("background-color", "yellow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="indice">
<li>Primo capitolo</li>
<li>Secondo capitolo
<ul>
<li>Sottocapitolo</li>
</ul>
</li>
<li>Terzo capitolo</li>
</ul>
<button id="eq">.eq()</button>
<button id="eq2">:eq()</button><br>
<button id="gt">.gt()</button> <!-- NO -->
<button id="gt2">:gt()</button><br>
<button id="lt">.lt()</button> <!-- NO -->
<button id="lt2">:lt()</button>
推荐答案
作为内置函数,它还不够有用.使用.eq()
代替:eq
允许jQuery使用querySelectorAll
来大幅提高性能.
It's not considered useful enough to be a built-in, I suppose. Using .eq()
instead of :eq
allows jQuery to use querySelectorAll
for a massive performance improvement.
在任何情况下,您都可以像这样使用.slice
:
In any case, you can use .slice
like so:
$("li").slice(0,4); // :lt(4)
$("li").slice(5); // :gt(4)
或者,将它们自己添加:
Alternatively, add them yourself:
$.fn.lt = function(n) {return this.slice(0,n);};
$.fn.gt = function(n) {return this.slice(n+1);};
示例:
$.fn.lt = function(n) {return this.slice(0,n);};
$.fn.gt = function(n) {return this.slice(n+1);};
$("div").lt(2).css("color", "blue");
$("div").gt(2).css("border", "1px solid red");
$("div").eq(2).css("background-color", "yellow");
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于为什么gt()和lt()只是jQuery选择器,而eq()也是一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!