I have some HTML drop-down menus, and then dependent upon the selection I then highlight the appropriate column heading in a table. I do this by changing the css class 开发者_如何学JAVAof that <td>
tag like so:
$("#searchcolour").attr("class", "filledselect");
$("#searchtask").attr("class", "filledselect");
$("#searchshape").attr("class", "filledselect");
$("#searchpivot").attr("class", "filledselect");
The highlighted column headings are dependent upon which ones have been selected. There can be as many as 20 column headings selected. This extra code for highlighting puts a 1-2 second delay on the updating of my page in IE (the jquery also filters the table results at the same time). The speed in other browsers is fine.
Is there a faster way I could achieve this effect?
Try this:
$("#searchcolour").addClass("filledselect");
$("#searchtask").addClass("filledselect");
$("#searchshape").addClass("filledselect");
$("#searchpivot").addClass("filledselect");
It depends on how you map the selections to the table cells. But I'm sure it won't take 1-2 seconds if you are using ID selectors like your example states, so there must be another bottleneck.
Why don't you apply an attribute to each menu item that matches the table id?
<ul id="menu">
<li><a href="#" rel="searchcolour">colour</a></li>
<li><a href="#" rel="searchtask">task</a></li>
</ul>
<script>
$('#menu a').click(function() {
$('#'+this.rel).addClass('filledselect');
});
</script>
Another way to optimize your existing code:
$(['colour','task','shape','viot']).each(function() {
$('#search'+this).addClass('filledselect');
});
You could cache the column selectors so the DOM elements don't have to be found each time:
var $searchcolour = $("#searchcolour");
var $searchtask = $("#searchtask");
var $searchshape = $("#searchshape");
var $searchpivot = $("#searchpivot");
...
$searchcolour.attr("class", "filledselect");
$searchtaskattr("class", "filledselect");
$searchshape.attr("class", "filledselect");
$searchpivot.attr("class", "filledselect");
Or instead of selecting each of the columns you could just add one set of classes to the table.
So do $('#id_for_table').attr('class', 'highlight-c1 highlight-c3') and add classes c1, c2, etc. to the cells you want highlighted. Then have CSS like this:
.hightlight-c1 .c1,
.hightlight-c2 .c2,
.hightlight-c3 .c3,
etc... { ... }
Alternatively you could name them after drop down options, so you only add one class to the table but the cells to be highlighted would have classes for each drop down that they should be highlighted for.
精彩评论