jQuery: remove class once element is clicked
I am stuck on a little jQuery problem. I have a collection of links (more than 50) generated from a php loop. When a user clicks on a link, the jQuery load event is called, and a php/mysql script (called page.php in the example below) is loaded into an empty div on the page.
I would like the class (".classy") to removed from the < a > tag and replaced with another class (".newclass"). This is so that the information is loaded only on the first click.
The html:
<a class='classy' name='marvin'>Click to toggle info</a>开发者_开发问答
<div id='marvin'></div>
The jQuery:
$(document).ready(function(){
$(".classy").click(function(){
var foo = $(this).attr("name");
$("#"+foo).load("page.php?id="+foo).slideToggle('fast');
$(this).removeClass('classy');
$(this).addClass('newclass');
return false;
});
});
Thanks!
Just because you change the class doesn't mean the click
event handler is removed from the link. You will need to unbind it manually or just add an if
statement that checks what class the link has.
Or use live
function to bind the click
event.
Not positive -- but you may need to do it like this (use $.live()) instead:
$(document).ready(function(){
$(".classy").live('click', function(){
var foo = $(this).attr("name");
$("#"+foo).load("page.php?id="+foo).slideToggle('fast');
$(this).removeClass('classy').addClass('newclass');
return false;
});
});
精彩评论