我正在使用 eq() 的 jQuery 功能,但它没有提供正确的结果
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div p:eq(1)").css("border","2px solid red");
});
});
</script>
</head>
<body>
<button>Click Me!</button>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
<div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
</body>
</html>
期望:
我预计有 2 行是红色的(第 5 行和第 8 行)。
结果:
另外,当我使用 lt() 时,我得到了错误的结果。
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div p:lt(2)").css("border","2px solid red");
});
});
</script>
</head>
<body>
<button>Click Me!</button>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
<div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
</body>
</html>
期望:
我预计有 4 行是红色的(第 6、7、11 和 12)。
结果:
I know that alternatively I can use, nth-child() , or nth-of-type(), nth-last(), or nth-last-child(), or :odd(), or :even(); or :nextAll() or :prevAll(), but I want to know, why is this not working! ;( .
谁能帮我解决问题出在哪里?
最佳答案
结果正确。因此,问题似乎出在您对这些选择器如何工作的期望上,因为您声明的结果是错误的,而实际上它们是正确的。1
div p:eq(1)
匹配第二个 div p
。只能有一个这样的元素,因为根据定义,:eq()
一次只匹配一个元素(如果没有匹配,则不匹配)。不能超过一个。
div p:lt(2)
匹配前两个 div p
元素。这些元素中最多只能有两个,因为您特别要求提供其中的前两个。
如果您要在每个 div
中寻找第二个 p
,那么您需要 .each()
div
元素并执行 .find('p:eq(1)')
和 .find('p:lt(2)')
分别。或者分别使用 div p:nth-child(2)
和 div p:nth-child(-n+2)
并放弃非标准的 jQuery 选择器和循环。
1 但我不怪你——语法使这些选择器成为 very confusing in terms of their functionality出于这个原因,我完全避免使用它们。
关于javascript - jQuery :eq(), :lt(), 和 :gt() 函数未提供预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463539/