使用单个函数如何调用两个不同的输入字段

时间:2015-04-03 09:28:52

标签: javascript

嗨,在下面的代码中,我将使用以下java脚本函数上传图像。第一个输入工作正常。同样如何在我传递id时调用第二个输入字段更改第一个和第二个图像显示相同。

HTML

 <div class="person_pic">
    <label>Please upload your photo</label><input  type='file' name="image" onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
    <label>Please upload your family photo</label>
    <input  type='file' name="image" onchange="readURL(this);" />
    <img id="blah1" src="#" alt="your image" />
</div>

的javascript

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(150)
                .height(200);
        };
        reader.readAsDataURL(input.files[0]);        
    }
    if (input.files && input.files[0]) {
        var reader = new FileReader();    
        reader.onload = function (e) {
            $('#blah1')
                .attr('src', e.target.result)
                .width(150)
                .height(200);
        };
        reader.readAsDataURL(input.files[0]);                    
    }
}

1 个答案:

答案 0 :(得分:1)

你可以尝试传递你想要改变的img元素的id。当你使用$('#blah')进行函数调用时,因此两个时间都显示相同的图像。你可以这样做:

<script>
        function readURL(input,x) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                x = '#'+x;
                reader.onload = function (e) {
                    $(x)
                        .attr('src', e.target.result)
                        .width(150)
                        .height(200);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
</script>
<div class="person_pic">
    <label>Please upload your photo</label>
    <input  type='file' name="image" onchange="readURL(this,'blah');" />
    <img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
    <label>Please upload your family photo</label>
    <input  type='file' name="image" onchange="readURL(this,'blah1');" />
    <img id="blah1" src="#" alt="your image" />
</div>
相关问题