简体   繁体   English

图像选择器不止一个

[英]Image selector more than one

I have a page and the page has two picture selectors. 我有一个页面,该页面有两个图片选择器。 I coded one of them for showing a picture when I select a picture file. 当选择图片文件时,我编码了其中一个用于显示图片。 But I want use them as separately. 但我想单独使用它们。 I tried it as attached code. 我尝试将其作为附加代码。 Could you please help me how can I do as separately them? 您能帮我分开我怎么做吗? Also how can I create separately clear buttons with PHP, Javascript or jQuery? 另外,如何使用PHP,Javascript或jQuery创建单独的清除按钮?

I tried as my code and it's working just for one selector, not for other. 我尝试作为我的代码,它仅适用于一个选择器,不适用于其他选择器。

<form id="form1">
    <input type="file" id="image-1-selector">
    <img src="#" id="first-image">
    <button type="reset" onclick="clearFile(event)">Clear</button><br /><br />

    <input type="file" id="image-2-selector">
    <img src="#" id="second-image">
    <button type="reset" onclick="clearFile(event)">Clear </button>
</form>
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#first-image').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#image-1-selector").change(function() {
    readURL(this);
});

var clearFile = function(event) {
    var output = document.getElementById('first-image');
    output.src = '';
};

Firstly you can DRY up your code by using classes instead of ids to select the elements. 首先,您可以通过使用类而不是ID来选择元素来干燥代码。 From there you can use DOM traversal methods (in this case next() and prev() ) to find the required elements to modify. 从那里可以使用DOM遍历方法(在本例中为next()prev() )来查找所需的要修改的元素。 Try this: 尝试这个:

<form id="form1">
    <input type="file" class="image-selector">
    <img src="#" class="preview">
    <button type="reset" class="clear">Clear </button><br /><br />

    <input type="file" class="image-selector">
    <img src="#" class="preview">
    <button type="reset" class="clear">Clear </button>
</form>
$(".image-selector").change(function() {
    var el = this;
    if (el.files && el.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $(el).next('.preview').prop('src', e.target.result);
        }
        reader.readAsDataURL(el.files[0]);
    }
});

$('.clear').click(function(event) {
    $(this).prev('.preview').prop('src', '');
});

Updated fiddle 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM