css选择器不是最后一个孩子不工作(需要纯css解决方案)

问题描述 投票:1回答:3

不知道为什么以下css选择器不起作用。想要在除DOM中的最后一个字段之外的所有字段中输入100。更喜欢纯css解决方案,即不在jQuery中添加.not(“:last”)。

$("input[id^=FIELD]:not(:last-child)").val("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="FIELD1" value="2">
<input id="FIELD2" value="2">
<input id="FIELD3" value="2">
<input id="FIELD4" value="2">
jquery css-selectors
3个回答
-1
投票

:last-child将无法工作,因为它需要一个parent所以使用:last-of-type

$('input[id^=FIELD]:not(:last-of-type)').val("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="FIELD1" value="2">
<input id="FIELD2" value="2">
<input id="FIELD3" value="2">
<input id="FIELD4" value="2">

与父母:

$('#mydiv input[id^=FIELD]:not(:last-child)').val("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
  <input id="FIELD1" value="2">
  <input id="FIELD2" value="2">
  <input id="FIELD3" value="2">
  <input id="FIELD4" value="2">
</div>

2
投票

StackOverflow片段会破坏您的代码。

你的代码没问题,但它需要parent的显式:last-child元素才能在StackOverflow片段中工作。

通常没有在StackOverflow上明确添加body,这将是自动插入的body元素,但由于与StackOverflow片段工作方式有关的一些奇怪原因,您明确需要在SO上添加父元素,以使选择器按预期工作。

编辑

我刚用CodePen和JSBin检查过,两者似乎都产生了同样的问题:

http://jsbin.com/ceguvogoza/1/edit?html,js,output

https://codepen.io/connexo/pen/KQYjKR

Proof your code works in a real world environment:

http://codestylers.de/last-child.html

function usingVanillaJs() {
  Array.from(document.querySelectorAll("input[id^='FIELD']:not(:last-child)")).forEach((input) => {
    input.value = 100;
  })
}

function usingJquery() {
  $("input[id^='FIELD']:not(:last-child)").val(200);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input id="FIELD1" value="2">
  <input id="FIELD2" value="2">
  <input id="FIELD3" value="2">
  <input id="FIELD4" value="2">
</div>
<button onclick="usingVanillaJs()">Vanilla JS</button>
<button onclick="usingJquery()">jQuery</button>

1
投票

$("input[id^=FIELD]").not(":last").val("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="FIELD1" value="2">
<input id="FIELD2" value="2">
<input id="FIELD3" value="2">
<input id="FIELD4" value="2">

对于CSS选择器,只需将last-child更改为last

$("input[id^=FIELD]:not(:last)").val("100");

如果您向选择器添加父级,last-child也会起作用:

 $("#parentDiv input[id^=FIELD]:not(:last-child)").val("100");
© www.soinside.com 2019 - 2024. All rights reserved.