jQuery事件处理程序关闭

When clicking a button for the first time, I'd like to have the event handler do a JSON request and return a function that handles any further clicks on the button. How can I achieve this without binding and unbinding event handlers on the button?

I'd like to just do the request and then let the returned event handler just show or hide a DOM element, without going through the entire function again (cache check etc.)

Pseudo code

var setuphandler = (function(){
    // get json, setup dom etc.
    // ...

    // return the actual
    // show/hide function here
    return function(){
       $(img).toggle();
    }
});

$('button').on('click', handler());

A sample JSFiddle here

Do you looking for something like this(link to fiddle)?

$(function(){
  var aboutpage = (function() {

    var $img;
    return function(data){
      if($img != undefined) {
        $img.toggle()
      } else {
        $.ajax({
          url:"http://fuckyeahbrutalism.tumblr.com/api/read/json",
          dataType: "jsonp", cache: false
        }).done(function(data) {
          var resp = data.posts[0]['photo-url-75'];
          $img = $('<img/>', {
              src: resp
          });
          $('#container').append($img);
        });
      }
    }
  })();
  $('#showcontent').on('click', aboutpage);
});

I don't know why you need to create your own deferred object at all here. It seems you can just assign aboutpage at the end of your .done() handler or just use a flag to keep track of whether this is the first time:

var aboutpage = function() {
      $.ajax({
            url:"your url here",
            dataType: "jsonp",
            cache: false
      }).done(function(data){
            var resp = data.posts[0]['photo-url-75'];
            var aboutEl = $('<img/>', {src: resp});
            $('#container').append(aboutEl);

            // assign aboutpage so the next click will just toggle
            aboutpage = function() {
                $('img').toggle();
            };            
      });
 };

$('#showcontent').on('click', function(){
     aboutpage();
};

You also could just use a flag:

function aboutpage() {
    if (!aboutpage.gotJSON) {
         // the first time this is called, retrieve JSON data
         aboutpage.gotJSON = true;
         $.ajax({
            url:"your url here",
            dataType: "jsonp",
            cache: false
         }).done(function(data){
            var resp = data.posts[0]['photo-url-75'];
            var aboutEl = $('<img/>', {src: resp});
            $('#container').append(aboutEl);
         });
    } else {
        // subsequent times, just toggle
        $('img').toggle();
    }
}