看下面的 HTML 代碼:
<div class="user-avatar-wrapper">
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button"></div>
<input class="file-upload" type="file" accept="image/*"/>
</div>
現在我想通過點擊觸發檔案上傳并呼叫 ajax .upload-button。
這就是我在 jQuery 中嘗試的方式,
$(document).on('click', '.upload-button', function(e) {
e.preventDefault();
//$(".file-upload").click();
$(this).next().trigger('click', function() {
var $data = { 'title': 'Title', 'file': 'myfile' };
$.ajax({
type: 'POST',
url: 'upload.php',
data: $data,
success: function(response) {
},
error: function(response) {},
});
});
});
但是,這段代碼對我不起作用。這意味著它沒有發送 ajax 請求。
希望有人可以幫助我。
uj5u.com熱心網友回復:
我認為您將觸發器與事件處理程式混為一談。
當您單擊 div 時,您應該觸發對檔案輸入的單擊,但您不會在那里傳遞回呼。您想為檔案輸入設定更改處理程式,以便在使用事件處理程式
選擇檔案時發出 ajax 請求。change
$(document).on('change', '.file-upload', function(e){
var data = new FormData();
data.append('title', 'Title');
data.append('file', this.files[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
processData: false,
contentType: false,
success: function(response) {
},
error: function(response) {},
});
$(this).prev().html(`↑${this.files[0].name}`);
});
$(document).on('click', '.upload-button', function(e) {
$(this).next().click();
});
.upload-button{
cursor:pointer;
}
.file-upload{
opacity:0.01
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="user-avatar-wrapper">
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button">↑</div>
<input class="file-upload" type="file" accept="image/*"/>
</div>
<div class="user-avatar-wrapper">
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button">↑</div>
<input class="file-upload" type="file" accept="image/*"/>
</div>
uj5u.com熱心網友回復:
您的 div 為空且不存在運行函式嘗試以下代碼:
<div class="upload-button"> </div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/503869.html
標籤:javascript jQuery 阿贾克斯 点击
