我想要做兩個上傳按鈕。一個是賬戶標識。多個JavaScript上傳按鈕只把內容放在一個
.col-sm-6
.wrapper
Account Logo
#account_logo
= image_tag @account.logo.url, :class => 'account_logo'
= file_field_tag 'account[logo]', :accept => 'image/png,image/jpeg'
%a.btn.btn-default{:href => '#'} Choose file
%span.notice
Only PNG or JPG please.
另一個是電子郵件標誌。
.col-sm-6
.wrapper
Email Logo
#email_logo
= image_tag @account.email_logo.url, :class => 'email_logo'
= file_field_tag 'account[email_logo]', :accept => 'image/png,image/jpeg'
%a.btn.btn-default{:href => '#'} Choose file
%span.notice
Only PNG or JPG please.
我已經添加了JavaScript,所以它適用於兩者。但是,有一些非常錯誤的事情發生。我添加了警報來嘗試和調試,並且他們告訴我即使點擊#account_logo按鈕,它也會進入#email_logo。可以一些JavaScript嚮導幫助我嗎?
:javascript
var logo = ["#account_logo", "#email_logo"];
for (var i = 0; i < logo.length; i++) {
var on_change = (logo[i] + ' input[type=file]');
var on_click = (logo[i] + ' a.btn');
var logo_img = (logo[i] + ' img');
$(document).on('click', on_click , function() {
alert("it is now " + on_click);
$(on_change).click();
alert("it is now " + on_change);
});
$(document).on('change', on_change, function() {
alert("it is now " + on_change);
var filelist = $(this).get(0).files;
var reader = new FileReader();
reader.onload = function (e) {
var url = e.target.result;
alert("it is now " + logo_img);
$(logo_img).attr('src', url);
}
reader.readAsDataURL(filelist[0]);
});
}
我懷疑代碼「reader.readAsDataURL(filelist [0]);」從你的JavaScript程序結束的第三行。 –
@ fumu7這是爲什麼? – alexia