JQuery in Internet Explorer - Selecting Table Columns
I'm trying to do some dynamic resizing of table columns on my page. Everything works fine in FF and Chrome, but (as usual) it seems to be breaking in Internet Explorer. After a lot of debugging, I've found开发者_高级运维 that the problem is caused by JQuery selectors don't work correctly in Internet Explorer, when you're dealing with tables. It would appear that if you are trying to select a column in a multi-row table, JQuery will only select the first column. Here is some quick code that will show the problem.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("td#2").css('background-color', 'red');
});
</script>
</head>
<body>
<table>
<tbody>
<tr><td id="1">1</td><td id="2">2</td></tr>
<tr><td id="1">1</td><td id="2">2</td></tr>
</tbody>
</table>
</body>
</html>
You will notice that in IE, only the first "2" is highlighted. It should (if I understand my own code correctly) highlight both of the 2's. Any ideas for workaround in this?
Instead of an ID (which has to be unique, your current issue), use a class
and $("td.2")
, or neither...and use :nth-child()
, like this:
$(document).ready(function(){
$("td:nth-child(2)").css('background-color', 'red');
});
With this your markup gets much simpler:
<table>
<tbody>
<tr><td>1</td><td>2</td></tr>
<tr><td>1</td><td>2</td></tr>
</tbody>
</table>
You can test it out here - and for comparison, here's the class version.
精彩评论