开发者

Jquery class removed after link click, but second click is still recognized

I'm having a little problem. I'm trying to use Jquery load() function to load in stuff on a page using AJAX. After the content has been loaded, and the link gets tapped on a second time, I need to loaded content to slideup/hide; And when the same link is clicked for the 3+ time, I need to just toggle the loaded content display, since it's already been loaded once.

My problem is that after clicking the link once, I remove the loadable class, but on the second click the same function executes as if the class were still there. Here is my HTML:

<a title="Food" id="food" class="loadable" href="get-taste/food">Food</a>
<div class="food_load_space"></div>

The link triggers the load and the data loads into .food_load_space. And here's my JS:

$(document).ready(function(){
  $('a.loadable').click(function(){ //executed upon link click 1;
    url = $(this).attr('href');
    linkid = $(this).attr('id');
    toload = url + ' #content-area';
    //now, remove loadable, add loaded and expanded
    $(this).removeClass('loadable');
    alert(toload);
    $('.' + linkid + '_load_space').load(toload);
    return false;
  }); //kill loadable

I'm also pla开发者_运维技巧nning on adding an .expanded class and a .loaded class so that the script knows at which state the link is in. But what happens is this function fires even if the .loadable class is gone.


The event has already been bound to the element, you need to manually unbind the event from the element(s) in question. This can be done by calling $(this).unbind('click');.

You may also wish to check if the element has the class in the event function.


The handler is bound the the element, not the selector.

If you only want it to exist for one click, use the one()(docs) method to bind it.

$('a.loadable').one('click', function(){ 
    // and so on...

It will be automatically unbound after the first click.


The reason your second click is recognized is because jQuery has already binded an action to your element. You can't unbind the event just by removing the class. The class was only there to help you select that element (and style your element).

To remove the event binding, in your click function, you should do something like:

$('a.loadable').click(function() {
    ...your other code...
    $(this).unbind('click');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜