2013-05-03 67 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