开发者

jQuery how to have a event only triggered once on clicking a div

This is probably pushing the limits of jquery.

I want to have the live() event triggered. But I only want to let it be triggered once using perhaps the one() event.

Currently I have the code blow. How do I restrict thi开发者_如何学运维s to only being called once.

    $(".sub-content").live('click', function() {
        var id = this.id;
        $.get("InfoRetrieve", { theid:id }, function(data) { addContent(data, id) } );
    });


There are a few ways of doing it. Firstly you can just use a marker:

<div class="sub-content not-loaded">...</div>

with:

$("div.sub-content.not-loaded").live("click", function() {
  $(this).removeClass("not-loaded");
  ...
});

Obviously you can do this the other way as well (add a class to mark that it's been loaded). I'm not 100% the above will be handled correctly with live() in which case:

$("div.sub-content.not-loaded").live("click", function() {
  if ($(this).hasClass("not-loaded")) {
    $(this).removeClass("not-loaded");
    ...
  }
});

will work.

Alternatively you can unbind the event.

$("div.sub-content").click(load_content);

function load_content() {
  $(this).unbind("click", load_content);
  ...
}

I'm not 100% sure that'll work with live() however (as live() may just rebind it).


You can use the die method:

$(".sub-content").live('click', function() {
   $(this).die('click');
   var id = this.id;
   $.get("InfoRetrieve", { theid:id }, function(data) { addContent(data, id) } );
});

I never tested it though.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜