2012-01-21 59 views
0

我正在处理这个html5文件上传器插件,但它有一个我无法理解和修复的错误。更改事件被触发两次而不是一次

jsfiddle link

这个插件的想法是一组功能附加到被点击,只有当它有针对性的按钮。

,但是当我在“按钮-1”点击 click事件中,“按钮-2”点击事件已在同一时间,当on change event正在发生触发。我认为改变事件必须被触发两次。

你可以尝试点击上传按钮,看看我的意思。

任何想法这个插件出了什么问题?

(function($){ 

    // Attach this new method to jQuery 
    $.fn.extend({ 

     // This is where you write your plugin's name 
     upload_file_html5: function(options) { 

      // Set the default values, use comma to separate the settings, example: 
      var defaults = { 
       objectSuperparent: '.media' 
      } 

      var options = $.extend(defaults, options); 
      var o = options; 

      var $cm = this.click(function(e){ 

       // <a> button is the object in this case. 
       var object = $(this); 

       // Get other info from the element belong to this object group. 
       var object_href = object.attr('href'); 
       var object_parent = object.parent(); 
       alert($cm.selector); 

       // Trigger the click event on the element. 
       // Due to security policies triggering click on the input type=file is not allowed/supported in some browsers and Opera is one of them. 
       //$('input[type=file]').trigger('click'); // or: 
       $(".upload-file",object_parent).click(); 

       return false; 

      }); 

      // Trigger ajax post when ever the file is changed by the user. 
      var $cm_2 = $(".upload-file").change(function(){ 

       // <input> is the object in this case. 
       var object = $(this); 

       var object_form = object.parent(); 
       var object_superparent = object.parents(o.objectSuperparent); 
       var path_config = $($cm.selector,object_superparent).attr('href'); 
       var path_post = object_form.attr('action'); 

       alert($cm.selector); 
       //alert(path_config); 

       .... 
       .... 

      }); 

     } 
    }); 

})(jQuery); 

回答

0

检查我的代码的变种:http://jsfiddle.net/es8Vh/3/ 基本jQuery插件结构:

$.fn.pluginName = function() { 
    return this.each(function() { // <-- this is important 
     // code here 
    }); 
}; 
+0

非常感谢这个答案,dfsq。但是,如何通过使用alert - 'alert($ cm.selector);''获取/返回点击按钮的名称(即'.button-1')? – laukok

+0

http://jsfiddle.net/es8Vh/5/'this'是你当前的DOM对象,$(this)是相应的jQuery对象。 – dfsq

+0

但是你最好不要依赖选择器,因为它可以是任何东西。例如:'#button1','.button1','#some> .button:first'等 – dfsq