3

OK so I was using a bit of jquery to select all the <a> tags on the page and if they link to an image file to add a zoom class to it for the purposes of a lightbox. This is the code which works

$(document).ready(function () {
$('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').addClass('zoom');
});

There is a problem with this though;

Say I have a link which just goes to another page but passes an image url as a GET variable in the URL the lightbox is activated as a result of this and fails because the link is not actually to an image. For example:

<a href="http://example.com/a-normal-page/?pic=http://example.com/pics/picture.jpg">Link text</a>

In the above instance the jQuery script will add the zoom class to this anchor even though it doesn't actually link to a picture. This wouldn't usually be an issue as you would leave the page to go to the link's destination before the lightbox has a chance to appear, but in times where a new tab/window is opened I get a failed lightbox coming up.

This is particularly prevalent on social media buttons such as Pinterest which passes an image url within the link.

[apologies for the title - I wasn't sure how best to phrase it. Please feel free to edit to something more suitable]

4

2 回答 2

2

you could add the zoom class only if href attribute doesn't contain a ? (or, in other words, a querystring is not included), e.g.

$(document).ready(function () {
    $('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').each(function() {
        if (this.href.indexOf('?') < 0) {
             $(this).addClass('zoom');
        }
    });
});
于 2013-01-29T12:30:23.410 回答
1

You can parse the href with a simple regex to check that the image is not in the query string, and filter out the false positives.

$(document).ready(function () {
    $imgLinks = $('a[href$=".png"], a[href$=".gif"], a[href$=".jpg"]');
    $imgLinks.filter(function() {
        return !$(this)
                .attr('href')
                .match(/^http\:\/\/.*\?.*http\:\/\/.*\.(png|gif|jpg)$/);
    })
    .addClass('zoom');
});
于 2013-01-29T12:33:35.897 回答