2013-05-03 71 views
1

我目前正在學習如何創建jQuery插件,並且已經創建了下面的代碼。我添加了自己的功能,並在爲我的插件添加默認設置後擴展了選項,但沒有任何事情發生。我甚至添加了一個警報 - 但它也沒有顯示。我的jQuery插件的語法有什麼問題?

這裏是我到目前爲止的代碼:

(function($){ 

    // Extend the Jquery Object with the Myedit Function 
    jQuery.fn.Myedit = function(options) { 

     // Default options 
     var defaults = { 
      width: 250, 
      height: 20, 
      url: "", 
      data: {}, 
      buttons: false 
     }; 

     // Extend the options with the onse the user provided 
     var options = $.extend(defaults, options); 

     return this.each(function() { 
      var object = $(this); 

      $(object).live('click', function() { 
       var input = $('<input />', {'type': 'text', 'name': $(this).attr('name'), 'value': $(this).html()}); 
       $(this).parent().append(input); 
       $(this).remove(); 
       input.focus(); 
      }); 

      $(object).live('blur', function() { 
       $(this).parent().append($('<span />').html($(this).val())); 
       $(this).remove(); 
      }); 
      $(this).hide(); 
     }); 
    }; 
    //return alert(object); 
})(jQuery); 

我在做什麼錯?

回答

3

試試這個: -

Demo

這只是一個指針,你應該尋找更多關於如何創建一個jquery plugin

(function($){ 

    // Extend the Jquery Object with the Myedit Function 
    jQuery.fn.Myedit = function(options) { 

      // Default options 
      var defaults = { 
       width: 250, 
       height: 20, 
       url: "", 
       data: {}, 
       buttons: false 
      }; 

      // Extend the options with the onse the user provided 
      var options = $.extend(defaults, options); 

      return this.each(function() { 

      var object = $(this); 
       var span = 'span[name=' + object.attr('name') + ']'; 
       var input = 'input[name=' + object.attr('name') + ']'; 

      $(document).on('click',span ,function() { 
       var input = $('<input />', {'type': 'text', 'name': $(this).attr('name'), 'value': $(this).html()}); 
       $(this).parent().append(input); 
       $(this).remove(); 
       input.focus(); 
      }); 

      $(document).on('blur',input, function() { 
       $(this).parent().append($('<span />',{name:object.attr('name')}).html($(this).val())); 
       $(this).remove(); 
      }); 

      }); 
    }; 
    //return alert(object); 
})(jQuery); 
$('span').Myedit(); 

幾件事情: -

  • 你到底藏身的元素,所以還不是都可見。
  • 您在不同的動作上動態地創建元素,因此僅綁定單擊事件是不夠的,您需要使用on()來使用事件委託。以便動態創建的元素具有從父級委派的事件,而不必再次綁定它們。
+1

謝謝你的好信息:D – test 2013-05-03 22:39:43

+0

沒問題..很高興它給了你一些提示或信息.. :) – PSL 2013-05-03 22:40:12