查找_only_包含图像的所有链接

时间:2013-06-09 13:52:52

标签: javascript jquery html css

为图像添加点击缩放功能,我使用以下代码切换类:

$(document).ready(function() {
    var imageLinks = $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif"], a[href$=".bmp"]');
    if (imageLinks.children('img').length) {
        imageLinks.children('img').each(function() {
            $(this).attr('title', '(click to enlarge image)');
        });
        imageLinks.click(function(e) {
            e.preventDefault();
            $(this).children('img').toggleClass('expanded');
        });
    }
    });

现在我的问题是,我可以在该页面上拥有文本链接,例如<a href='file.png'>text</a>,并且它们会被此代码破坏。

有没有办法只选择图像链接(<a href='file.png'><img src='file.png'></img></a>)而不是所有图像文件链接?

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以使用has声明:

var imageLinks = $('a').filter(':has(img)');

或者相同:

var imageLinks = $('a:has(img)');

答案 1 :(得分:0)

我相信这会奏效:

var $images = $('a > img');
$images.attr('title', '(click to enlarge image)');
$images.parent().click(function(e) {
    e.preventDefault();
    $(this).children('img').toggleClass('expanded');
});

示例jsFiddle:http://jsfiddle.net/UHkh7/

如果img并非始终是a标记的直接后代,您可以将选择器更改为'a img',但是您需要将$images.parent()更改为$images.parents('a')[0]