使用alt文本查找图像标记

时间:2010-05-26 15:36:51

标签: javascript image attributes tags

我想知道是否可以使用Javascript通过其alt文本查找图像标记。例如,我有这个标签:<img src="Myimage.jpg" alt="Myimage">是否有办法通过查找“Myimage”alt属性来获取标签?

4 个答案:

答案 0 :(得分:11)

毫无疑问,很快就会发布一个jQuery解决方案。要做到这一点,以下将起作用:

function getImagesByAlt(alt) {
    var allImages = document.getElementsByTagName("img");
    var images = [];
    for (var i = 0, len = allImages.length; i < len; ++i) {
        if (allImages[i].alt == alt) {
            images.push(allImages[i]);
        }
    }
    return images;
}

var myImage = getImagesByAlt("Myimage")[0];

答案 1 :(得分:8)

您可以使用JQuery执行此操作。以下JQuery代码将返回任何图像,其alt标记设置为“Myimage”:

$('img[alt="Myimage"]').

然而,使用图像标记的id属性会更容易,性能更高。

答案 2 :(得分:4)

"data"

答案 3 :(得分:0)

如果NodeList实现了Iterable,那就不会那么难了。这个实现将过滤器放入NodeList的原型中,这可能与每个人的口味都不匹配,但我更喜欢简洁地访问我的数据结构。

<html>  
    <head>
        <script type="text/javascript">
            // unfortunately NodeLists do not have many of the nice Iterate functions
            // on them, here is an incomplete filter implementation
            NodeList.prototype.filter = function(testFn) {
                var array = [] ;
                for (var cnt = 0 ; cnt < this.length ; cnt++) {
                    if (testFn(this[cnt])) array.push(this[cnt]) ; 
                }
                return array ;
            }

            // loops through the img tags and finds returns true for elements that
            // match the alt text
            function findByAlt(altText) {
                var imgs = document.getElementsByTagName('img').filter(function(x) {
                    return x.alt === altText ;
                }) ;

                return imgs ;

            }

            // start the whole thing
            function load() {
                var images = findByAlt('sometext') ;

                images.forEach(function(x) {
                    alert(x.alt) ;
                }) ;
            }

        </script>
    </head>

    <body onload="load()">
        <img src="./img1.png" alt="sometext"/>
        <img src="./img2.png" alt="sometext"/>
        <img src="./img3.png" alt="someothertext"/>
    </body>
</html>
相关问题