问题
I am using the .eq() method to select a specific child element of a known element. It appears that the element indices are different in IE and in Chrome/FF, as .eq(2) returns different values depending on browser. (The element I'm looking for shows up as .eq(2) in FF/Chrome, but .eq(3) in IE)
For example,
alert($(this).parent().children().eq(2).text());
shows different results depending on the browser.
Here's the markup in question:
<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>
(I stripped out attributes, inline css etc -- same thing happens without those in place).
Is there a better way of doing this?
回答1:
I should think it is to do with empty text nodes, Firefox will not register the white space between say, the <span> and the <input> tag, where as IE will, so for FF the second node will be the <input> tag (<span><input>) where as it it will be the text node (<span>-empty text node-<input>).
EDIT:
After some testing (Previous answer was just a common problem I run into so presumed it may have been the same for you), The problem is that IE picks up your closing tag as an element in the dom.
If you change your code to short closing tags, ie:
<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>
Then it should work as predicted.
Just for reference my whole test script (only alerting the text):
<!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>
来源:https://stackoverflow.com/questions/2407308/jquery-eqx-returns-different-element-in-ie-than-in-ff-chrome