2
與jQuery周圍玩奇怪的行爲,我試圖動態乘上一個點擊按鈕的表單元素(一個文件上傳框)。下面的代碼:使用jQuery的clone()和POST請求
$(document).ready(function() {
$('#new-image').click(function() {
var idx = $('.input.file').size();
var upload = $('.input.file:first-child').clone();
$(upload.find('label')).attr('for', 'Attachment'+idx+'File');
$(upload.find('input[type=file]')).attr('name', 'data[Attachment]['+idx+'][file]');
$(upload.find('input[type=file]')).attr('id', 'Attachment'+idx+'File');
upload.insertBefore('#new-image');
return false;
});
});
的問題是,如果我嘗試和修改我結束了在POST請求是這樣的輸入的名字 - 從Chrome的(開發版本)控制檯拍攝,也borks在Firefox( 3.6)。
------WebKitFormBoundaryMXYcXg2mbP1HZsVJ
Content-Disposition: form-data; name="data[Attachment]​[3]​[file]"; filename="logo.png"
Content-Type: image/png
這不是因爲字符串連接,我嘗試了一個硬編碼值,並且請求中的怪異仍然存在。我在這裏錯過了什麼,或者這是jQuery中的錯誤?
(如果你想知道,這個名字屬性格式 - data[...
來自CakePHP的)
更新
看來問題是不是因爲.attr()
,而是因爲.clone()
。我相應地修改了這個問題。
我的印象是,這工作:
upload.find('input[type=file]').name = 'data[Attachment]['+idx+'][file]';
// wrong -> find returns a jQuery object and setting name has no effect
,因爲我沒有嘗試添加多個文件,我只是想最後添加的場:)。它甚至沒有以正確的形式工作:
upload.find('input[type=file]').get(0).name = 'data[Attachment]['+idx+'][file]';
// I still get mumbo-jumbo in the post, between the ][ characters
我只是想不clone()
和它的作品,這次是真的:)。
$('#new-image').click(function() {
var idx = $('.input.file').size();
var upload = $('<div class="input file"><label for="Attachment'+idx+'File">File</label><input type="file" name="data[Attachment]['+idx+'][file]" id="Attachment'+idx+'File"></div>');
upload.insertBefore('#new-image');
return false;
});
沒有人有任何想法,爲什麼clone()
行爲這種方式?
它不應該是:'VAR IDX = $(」輸入.file')長度;'? – 2011-03-22 22:34:37
'size()'也適用:http://api.jquery.com/size/。我應該切換到'長度',但這比實驗更能體現出生產的實驗,所以我沒有付出太多的關注:)。 – 2011-03-22 22:37:43
試圖重現並失敗:http://jsfiddle.net/yahavbr/tKp4z/你能否更新那裏的代碼並重現你描述的內容? – 2011-03-22 22:48:16