1

我编写了这段代码及其工作,但是当我选择图像时,所有输入都查看相同的图像,不仅是我将图像添加到的那个..

<html lang="en">
<head>
    <title>Change image on select new image from file input</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    <ul>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
        <li>
            <input type="file" name="file" class="profile-img">
            <img src="" class="profile-img-tag" width="200px" />
        </li>
    </ul>

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.profile-img-tag').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    $(".profile-img").change(function(){
        readURL(this);
    });
</script>


</body>
</html>

只是不能分别为每个输入做它。

4

1 回答 1

0

只需更改单击输入旁边的图像属性:

$(input).next().attr('src', e.target.result);

<html lang="en">
<head>
<title>Change image on select new image from file input</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<ul>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
    <li>
        <input type="file" name="file" class="profile-img">
        <img src="" class="profile-img-tag" width="200px" />
    </li>
</ul>

<script type="text/javascript">
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $(input).next().attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$(".profile-img").change(function(){
    readURL(this);
});
</script>


</body>
</html>

于 2020-02-15T04:39:10.610 回答