2013-04-16 48 views
0

我想使用jQuery标题标签添加到类LS-拇指主动,我这一点,得到了到:使用jQuery添加标题标签基于每个图像名称

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){ 
tooltip = "mouseover"; 

$('.ls-thumb-active').attr('title', tooltip); 

$('.displaytitle').html($('.ls-thumb-active').attr('title')); 
});//]]> 

</script> 

的问题是,我希望它显示实际的img名称作为工具提示变量,而不会在末尾显示.jpg。这可能吗?

回答

0

由于扩展是两种:

  • 的.jpg
  • png格式
  • .gif注意:

您可以使用子末削减四个大字,并加入到标题。

$('.ls-thumb-active').attr('title', substr(tooltip, 0, strlen(tooltip) - 4)); 
+0

我认为这将是更安全的使用上一点性格分裂法 “”并删除获得的数组的最后部分 – AnthonyLeGovic

+2

如果扩展名是'.jpeg',该怎么办? – DarkAjax

+0

哈哈...没有想到它! –

2

您可以通过“分割”您的img名称轻松完成此操作。所以我们说了var形象是你的形象的名字,像这样:

var image = 'something_unusual.jpg'; 

你可以得到图像名称如下:

var image_name = image.split('.')[0]; 

然后,当然,你添加它以同样的方式你做第一个:

$('.ls-thumb-active').attr('title', image_name); 

请注意,我使用的方法“拆分”,它分裂你的形象名称的caracter“。”。所以如果图像出于某种原因被视为“。”以他的名义,这可能会打破。您也可以使用最后一个点的索引来进行子串,拼接等。但是在这个例子中,如果图像名称中没有点,那么无论文件扩展名是什么,它都可以很好地工作。 希望这有助于。

+0

如果图像名称有“。”,该怎么办?说'new.image.jpg'。这不起作用。 * ps:我删除了downvote!* –

+1

hehe感谢您删除downvote。正如你所看到的,当我发布答案时,我自己就想到了它。 substr会很好地符合最后一个点的索引。或者你可以.split('。'),然后'.pop()'(删除最后一个数组元素),然后'.join('。')'!这就是我喜欢的JavaScript!有一百万个解决方案可用;) – Bene

3

你可以拿出的东西,如下面的图像名称的“.JPG”的一部分,这将让你的什么名字剥离后的任何扩展你得到:

var imageName = imageElementYouAreGettingSomewhere.src; 
imageName = imageName.substr(0, imageName.lastIndexOf('.')); 

$('.displaytitle').attr('title', imageName); 
1

由于这是每个图像都需要的,您需要遍历所有图像并设置title属性。

$('.ls-thumb-active').each(function() { 
    var imgName = $(this).attr('src').split('.')[0]; 
    $(this).attr('title', imgName); 
}); 
+0

你甚至可以用'attr'来做到这一点。查看何时使用“每个”,因为它是一个昂贵的功能。 –

+0

是的,没有必要循环... –

0

使用此代码:

<script type='text/javascript'> 
jQuery(document).ready(function($) { 
    tooltip = "mouseover"; 
    thumActive = $('.ls-thumb-active'); // Cached object 
    // Get the source name of the image 
    thumbImageSrc = $('.target-of-the-image').attr("src"); 
    // To slice from the last '/' if there is no '/' then slice from the very start 
    thumbImageNameFirstSlice = (thumbImageSrc.lastIndexOf('/') ? thumbImageSrc.lastIndexOf('/') + 1 : 0); 
    // And will slice to the last '.' 
    thumbImageName = thumbImageSrc.slice(thumbImageNameFirstSlice, thumbImageSrc.lastIndexOf('.')); 
    // Your code =) 
    thumActive.attr('title', tooltip); 
    // Assign the name to the '.displaytitle' 
    $('.displaytitle').html(thumbImageName); 
}); 
</script> 

有一个的jsfiddle:http://jsfiddle.net/Np6FG/1/