如何在jQuery中将文件上传函数的值传递到另一个函数?
Hey there! The issue you're running into is all about variable scope—right now, your image variable is defined inside the onchange function, which means it only exists within that function's context. Other functions (like your .applyTeacher click handler) can't reach it. Let's fix this with a few straightforward solutions:
Solution 1: Declare the variable in a shared scope
The simplest fix is to define image in a scope that both functions can access (like the global scope, or a parent function wrapping both handlers). Here's how to adjust your code:
// Declare the variable outside both functions so it's shared let image; var fileupload = document.getElementById("fileup"); $('.upload-btn').on('click',function(){ var sb_field = $(this).parent().find('input[type="file"]'); sb_field.click(); }); fileupload.onchange = function (){ // Assign the value to the shared variable instead of creating a new local one image = $('#fileup')[0].files[0]; } $('.applyTeacher').on('click', function () { console.log(image); // Now this will work! });
Solution 2: Store the image in an element's data attribute
If you want to avoid global variables (a good practice to prevent scope pollution), you can store the selected image directly on the file input element using jQuery's data() method:
var fileupload = document.getElementById("fileup"); $('.upload-btn').on('click',function(){ var sb_field = $(this).parent().find('input[type="file"]'); sb_field.click(); }); fileupload.onchange = function (){ var image = $('#fileup')[0].files[0]; // Store the image in the element's data store $('#fileup').data('selectedImage', image); } $('.applyTeacher').on('click', function () { // Retrieve the image from the element's data let image = $('#fileup').data('selectedImage'); console.log(image); });
Both approaches will let you access the uploaded image in your .applyTeacher click handler. The second method is cleaner for larger codebases, while the first is quick and simple for smaller projects.
内容的提问来源于stack exchange,提问作者Rob

