0

我是使用 jQuery 的初学者并且遇到了一个问题。

我制作了一个画廊,并添加了画廊链接以方便标签用户。例如,如果您添加一个收藏链接,访问该页面将看到正确的图像,因为哈希标签存在于链接中。

画廊几乎可以工作了,实际上我只是想添加一个类来制作选定的图像集。

$gallery = window.location.hash;

//If have no hashtag, adds the class on the first image
if( $gallery == '')
    jQuery('.gallery-nav ul li').children('a').first().addClass('current');
else
{
    jQuery('.gallery-nav ul li').each(function($i){
        $link_hash = jQuery(this).find('a').attr('href');

        if( $link_hash == $gallery)
        {
            alert ( $link_hash );
        }
    });
}

直到第一部分,“如果没有标签,在第一张图片上添加类”工作正常,但我不知道如何。例如,如果链接是:http://example.net/gallery.php#3,我想在第三个链接上添加类。

在上述函数中,它正确显示了警报。当它到达选定的链接时,它会显示警报。但我不知道如何在链接中添加类。

有人可以帮我吗?谢谢。

4

1 回答 1

0

您可以直接使用attribute-ends-with-selector(docs)选择该元素,以选择以.href结尾的元素$gallery(我假设少于十个。)

如您所见,$gallery被连接到选择器字符串中。

else {
    jQuery('.gallery-nav ul li a[href$=' + $gallery + ']').addClass('current');
}
于 2011-01-21T19:30:49.497 回答