开发者

Tell jQuery to execute certain code only once

Is there any way to tell jQuery to do something only once? E.g. right now, I need jQuery to on click of div, append some HTML. Then, every time someone clicks that div again it toggles hide/show. Is there a way开发者_运维知识库 to do this? I'm trying not to be too confusing.

EDIT: Solved!


Use the one method.

For example:

$('#myDiv').one('click', function() {
    $(this).append('...').click(function() { ... });
});


There are multiple ways of doing this.

Firstly you could use a marker and then remove it:

<div id="mydiv" class="not-initialized">
  ...
</div>

with:

$("#mydiv").click(function() {
  if ($(this).hasClass("not-initialized")) {
    $(this).removeClass("not-initialized");
    // append content
  } else {
    $(this).toggle();
  }
});

Secondly, you could change event handlers:

$("#mydiv").click(append_content);

function append_content() {
  ...
  $("#mydiv").unbind("click", append_content).click(toggle_display);
}

function toggle_display() {
  $(this).toggle();
}

Or you could do things like testing the div to see if the content is there.


You're looking for the one method. Alternatively you could use hide or show instead of toggle.


jQuery's toggle: http://docs.jquery.com/Effects/toggle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜