我有一些 html 元素:
<img id="preview_image" alt="" src="" width="100px" height="120px">
<br>
<input type="file" name="user_image" id="user_image" onchange="preview(this);">
这里是js:
function preview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview_image')
.attr('src', e.target.result)
.width(100)
.height(120);
};
reader.readAsDataURL(input.files[0]);
}
}
当我选择一张图片时,它会立即预览。
我现在想要的是:首先,选择一个图像(但现在不是预览),然后单击超链接,将显示该图像。超链接是这样的:
<a href="javascript:void(0)" onclick="preview2()">Click to preview</a>
preview2 = function(){
//what should I do here (using Jquery)
}
非常感谢!
最佳答案
首先,使用onclick
是非常糟糕的做法。相反,使用 jQuery 的事件绑定(bind)。无论哪种方式,这段代码都可以解决问题:
<a id="previewButton">Click here to preview</a> <!-- initially, the button is disabled -->
<script type="text/javascript">
function preview (input)
{
$("#previewButton").hide (); // don't show preview until file loaded
// implementation code
reader.onload = function (e) {
$("#previewButton").show () // show the button
.click (function() {
$("#preview_image").attr () // your old loader code
}
}
}
关于javascript - 如何在 Jquery 中预览图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7469504/