2013-04-26 53 views
0

我做了一个自定义的jQuery扩展来处理上传文件。为什么我的jQuery扩展的功能“静态”?

我的剥离版本:http://jsfiddle.net/6huV6/

我的完整版:http://jsfiddle.net/LQrJm/

我的问题是buildBondye被称为2倍,但我的延长加2×2滴管和按钮..

如何我解决这个问题吗?

+0

请遵循以下准则:http://docs.jquery.com/Plugins/Authoring – Dom 2013-04-26 14:54:03

+0

只需调用buildBondye()而不是每个语句。 – 2013-04-26 14:57:55

回答

6

您得到4个,因为对于匹配元素集合中的每个元素,您将调用buildBondye函数,该函数又调用addButtonaddDropper函数。这些函数使用$this,它是整个匹配元素集(所以它们都是),不仅是.each()的迭代元素。

你可以通过一个参考的单个元素,以这两个功能,并使用替代解决这个问题:

var buildBondye = function() { 
    // inside buildBondye this refers to the specific element for the iteration of .each() 
    // different to the this inside the $.fn.bondye function 
    addButton(this); 
    addDropper(this); 
} 

var addDropper = function (element) { 
    $dropper = $('<input type="text" readonly />'); 
    $dropper.val('drop here'); 
    $(element).after($dropper); 
} 

var addButton = function (element) { 
    $button = $('<input type="button" />'); 
    $button.val('browse'); 
    $button.bind('click', function() { 
     $(element).trigger('click'); 
    }); 
    $(element).after($button); 
} 

this updated jsFiddle看看。

+0

+1。如果OP不理解他正在使用的闭包,那也很好理解。 – 2013-04-26 15:00:03

+0

谢谢!我认为'$ this = this;'部分有当前的'.bondye'我现在明白了:) – 2013-04-26 15:04:09