0

to add a click-to-zoom feature to images, I used the following code to toggle a class:

$(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');
        });
    }
    });

Now my problem is, I could have text links, like <a href='file.png'>text</a> as well on that page, and they are broken by this code.

Is there a way to select only image links (<a href='file.png'><img src='file.png'></img></a>) instead of all links to image files?

Thanks in advance!

4

2 回答 2

2

你可以使用has声明:

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

或相同:

var imageLinks = $('a:has(img)');
于 2013-06-09T13:57:28.093 回答
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]

于 2013-06-09T13:59:08.177 回答