gpt4 book ai didi

javascript - jquery index()方法问题按属性值选择

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:50 25 4
gpt4 key购买 nike

有人可以拍一个look at this吗? ?

您会看到第一个警报打印 -1 而我期待的是 1。有人知道为什么吗?

fiddle 的基本代码:

<input type="checkbox" value="0" />0
<input type="checkbox" value="1" />1
<input type="checkbox" value="2" />2
<input type="checkbox" value="3" />3
alert($(':checkbox').index("input[value='1']"));
alert($(':checkbox').index("input[value='0']"));

最佳答案

您将选择器颠倒了:

示例: http://jsfiddle.net/RaV35/

 // element---v    collection----------v
alert($("input[value='0']").index(":checkbox"));
alert($("input[value='1']").index(":checkbox"));

通过 index()[docs] 时方法选择器,您想要索引的单个元素是调用 .index() 的元素。

您传递给 .index() 的选择器表示测试原始 jQuery 对象中元素的集合。

当原始 jQuery 对象(左侧)也包含一个集合时,只有第一个对象会针对右侧的选择器进行索引测试。这就是 value="0" 的原因。

 //   v--- only the first is tested (and it has value="0")...
$(':checkbox').index("input[value='0']")
// ----------------------^ ...and it is at index 0 of this "collection"

关于javascript - jquery index()方法问题按属性值选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com