我正在使用 .eq() 方法来选择已知元素的特定子元素。 IE 和 Chrome/FF 中的元素索引似乎不同,因为 .eq(2) 根据浏览器返回不同的值。 (我要查找的元素在 FF/Chrome 中显示为 .eq(2),但在 IE 中显示为 .eq(3))
例如,
alert($(this).parent().children().eq(2).text());
根据浏览器显示不同的结果。
这是有问题的标记:
<div>
<span>
<input onclick="player.search.Groupings($(this).parent().children().eq(2).text(), $(this).parent().children().eq(0).is(':checked'));" type="checkbox"></input>
<span>Fake Initiative A</span><span>1</span>
</span>
<span>
<input onclick="player.search.Groupings($(this).parent().children().eq(2).text(), $(this).parent().children().eq(0).is(':checked'));" type="checkbox"></input>
<span>Initiative B Not Real</span><span>2</span> </span>
</div>
(我删除了属性、内联 css 等——没有这些属性,同样的事情也会发生)。
有更好的方法吗?
最佳答案
我认为这与空文本节点有关,Firefox 不会注册 和 <input> 标签之间的空白,而 IE 会注册,所以对于 FF 来说,第二个节点将是 <input> 标记 (<input>),因为它将是文本节点 (-空文本节点-<input>)。
编辑:
经过一些测试(之前的答案只是我遇到的一个常见问题,所以假设它对您来说可能是相同的),问题是 IE 将您的结束标记作为 dom 中的元素。
如果您将代码更改为短结束标记,即:
<div> <span> <input type="checkbox" /> <span>Fake Initiative A</span><span>1</span> </span> <span> <input type="checkbox" /> <span>Initiative B Not Real</span><span>2</span> </span> </div>
然后它应该按预期工作。
仅供引用我的整个测试脚本(仅提醒文本):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <title>Title here!</title> <script type="text/Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/Javascript"> $(function(){ $("input:checkbox").bind('click', function(){ alert($(this).parent().children().eq(2).text()); }); }); </script> </head> <body> <div> <span> <input type="checkbox" /> <span>Fake Initiative A</span><span>1</span> </span> <span> <input type="checkbox" /> <span>Initiative B Not Real</span><span>2</span> </span> </div> </body> </html>
关于jQuery .eq(x) 在 IE 中返回与 FF/Chrome 中不同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2407308/