如何在jQuery中获取元素类,从数组中分配字符串并将它们作为属性返回?

3

我有一个包含在图片映射中的重复类别为.fancybox。

<map name="Map1" id="Map1">
  <area shape="rect" coords="609,235,834,335" href="about.html" class="fancybox" rel="iframe" />
  <area shape="rect" coords="649,546,807,565" href="info.html" class="fancybox" rel="iframe" />
  <area shape="rect" coords="670,566,781,582" href="help.html" class="fancybox" rel="iframe" />
</map>

<map name="Map2" id="Map2">
   <area shape="rect" coords="609,235,834,335" href="contact.html" class="fancybox" rel="iframe" />
   <area shape="rect" coords="649,546,807,565" href="comments.html" class="fancybox" rel="iframe" />
</map>

我有一个jQuery数组,想要添加Title属性。我知道它可以在HTML中添加,但是由于图像映射是由服务器端CMS生成的,我无法进行编辑,因此需要通过这个客户端数组提供。

$(document).ready(function() {
    var mapDetails = [   
        //Map1   
        "About Page",
        "Information",
        "Get Help",
        //Map2
        "Contact Me",
        "Post Comments"
        ]; 

   $('.fancybox').each(function() {
    $(this).attr('title', mapDetails[$(this).index()]); 
   })
});

我的问题是,在Map2上它从数组的开头重新开始,而不是像页面上第四个.fancybox一样继续在数组中进行。我猜想这是因为它们有不同的父元素。我是否可以选择所有的.fancybox元素,将它们分配给数组中的标题,并使用jQuery更新HTML,以便页面上所有的.fancybox类按它们出现的顺序从数组中分配? 我也尝试使用相同结果的“区域”选择器:
   $('area').each(function() {
    $(this).attr('title', mapDetails[$(this).index()]); 
   })

你应该使用传递给each回调的索引参数。 - Manuel Leuenberger
2个回答

2
由于没有传递参数调用了index(),它会返回每个元素相对于其同级元素的索引。因此,当从一个<map>元素转到另一个时,该索引将“重置”。
您可以使用each()提供的index参数来代替。
$(".fancybox").each(function(index) {
    $(this).attr("title", mapDetails[index]);
});

那样,索引将为每个元素递增,并且不会在地图之间重置。

你是传奇!!谢谢,我现在开始学习数组和jQuery - 这就解释了为什么我在过去几个小时里遇到这么多问题!非常感激你如此快速和信息量丰富的回答。再次感谢。 - JayDee

1
你应该使用each()index
   $('.fancybox').each(function(index, el) {
      $(this).attr('title', mapDetails[index]); 
   })

谢谢Nicola,(index, el)中的el是什么意思? - JayDee
@JayDee 它是迭代的当前元素(您也可以使用“this”引用迭代的当前元素) - Nicola Peluchetti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接