使用jQuery显示有关多个图像的文本信息

时间:2018-11-21 22:40:55

标签: javascript jquery

我正在使用jQuery创建一种独立的本地Web应用程序, 1)从用户那里获取图像文件名的列表(假设图像都与.html文件位于同一文件夹中) 2)对于每个图像,使用image.naturalWidth和image.naturalHeight显示缩略图,图像文件名和图像的实际尺寸。

我设法使它按我想要的方式工作-除了对于所显示的每个图像,伴随的文本信息都在其各自的次数与图像总数相同的次数之后显示-即,文本在那里如果总共有一张图像,则一次;如果总共有2张图像,则两次;如果有3张图像,则三倍,等等。

我认为它与$('img')的使用有关。但是,我无法弄清楚如何以不同的方式构造它,甚至无法用短语表达搜索答案。

我尝试做一个JSfiddle,但是由于某种原因,我无法从任何远程服务器上加载图像。但这对我来说很好,因为我通常想在本地获取图像尺寸的列表。

每个图像的增量编号ID都是旧版本的痕迹,但是我想保留它,以防我想到它的其他用途-除非那是引起问题的原因。

仅包含用于上下文的网页样板...

    <!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    img {
        width: 250px;
    }

    .inner {
        font-size: 12px;
    }
    </style>
</head>

<body>
    <textarea textarea id="image_list" rows="10" cols="70" /></textarea>
    <input type='button' value='add to list' id='add' />
    <table>
        <div class="inner">
            <ul id='list'></ul>
        </div>
    </table>
    <script src="vendor/jquery.js"></script>
    <script>
    $(function() {
        /* increase ID by 1 for each iteration */
        var n = 0;

        function increment() {
            n++;
            return n;
        }
        /* add image thumbnail and dimensions on click */


        document.getElementById("add").onclick = function() {
            var arrayOfLines = $('#image_list').val().split('\n');
            $.each(arrayOfLines, function(index, item) {

                var text = arrayOfLines[n];
                increment();
                /* var text = arrayOfLines[].value; //.value gets input values */

                //Now construct a quick list element
                var li = '<li class="test" id="' + n + '">' + '<img src="' + text + '">' + '</li>';

                $('#list').append(li);

            });

            $('img').load(function() {
                $('img').each(function() {
                    var image = this;
                    var theWidth = image.naturalWidth;
                    var theHeight = image.naturalHeight;

                    $(this).parent().append(' - ' + $(this).attr("src") + ' - ' + theWidth + 'x' + theHeight + ' ');
                });
            });
        };


    });
    </script>
</body>

</html>

0 个答案:

没有答案