Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - Emulate a file upload click in jQuery

I have an <img ... /> tag that I have bound a click event to in jQuery. When it is clicked I'd like to have it emulate the click of a button on the file upload to open the file system browse pop-up. I've tried these things within the click function and had no success:

...
$(".hiddenUploadBtn").click();
...

...
$(".hiddenUploadBtn").select();
...

...
$(".hiddenUploadBtn").submit();
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just wrap the img in a label and set the for attribute to the file input. Works for any kind of content and it's built into the spec. You can even hide the file input at that point.

<input type="file" id="fileUpload"><br>
<label for="fileUpload">
    <img src="https://www.google.com/images/srpr/logo11w.png" />
</label>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...