Add CSS class with JavaScript
I have the following code that makes check-boxes a little fancier by adding an image sprite to the check-box.
Javascript:
$(document).ready(function() {
/* see if anything is previously checked and reflect that in the view*/
$(".checklist input:checked").parent().addClass("selected");
/* handle the user selections */
$(".checklist .checkbox-select").click(
function(event) {
event.preventDefault();
$(this).parent().addClass("selected");
$(this).parent().find(":checkbox").attr("checked", "checked");
}
);
$(".checklist .checkbox-deselect").click(
function(event) {
event.preventDefault();
$(this).parent().removeClass("selected");
$(this).parent().find(":checkbox").removeAttr("checked");
}
);
});
CSS:
.checklist
{
list-style: none;
margin: 0;
padding: 0;
}
.checklist li
{
float: left;
margin-right: 10px;
background: url(resources/i/checkboxbg.gif) no-repeat 0 0;
width: 105px;
height: 150px;
position: relative;
font: normal 11px/1.3 "Lucida Grande" , "Lucida" , "Arial" ,Sans-serif;
}
.checklist li.selected
{
background-position: -105px 0;
}
.checklist li.selected .checkbox-select
{
display: none;
}
.checkbox-select
{
display: block;
float: left;
position: absolute;
top: 118px;
left: 10px;
width: 85px;
height: 23px;
background: url(resources/i/select.gif) no-repeat 0 0;
text-indent: -9999px;
}
.checklist 开发者_运维问答li input
{
display: block;
}
a.checkbox-deselect
{
display: none;
color: white;
font-weight: bold;
text-decoration: none;
position: absolute;
top: 120px;
right: 10px;
}
.checklist li.selected a.checkbox-deselect
{
display: block;
}
.checklist li label
{
display: block;
text-align: center;
padding: 8px;
}
Markup:
<ul class="checklist">
<li>
<asp:CheckBox ID="CheckBox1" Text="<img src='' />Option" runat="server" />
<a class="checkbox-select" href="#">Select</a>
<a class="checkbox-deselect" href="#">Cancel</a>
</li>
</ul>
When the check-box is selected, class="selected"
is added to the <li>
.
The trouble is that if the user hits the back button, the check-boxes are still selected (page cached), but the css is not re-applied. I could always add some cache-control so the browser loads a fresh copy of the page each time, so the check boxes will not be checked, but I would rather re-apply the the class to the list item.
Each <ul class="checklist">
is wrapped in an asp.net panel that is rendered as a div with an id of ct100_ContentPlaceHolder1_Panel1 - how would I loop through each check-box in that panel and re-attach the css class if the check-box is checked?
Thanks in advance!
You can do this on load using the :checked selector:
$('.checklist :checked').parent().addClass('selected');
精彩评论