How do I take the class of an element, assign them strings from an array, and return them as attributes in jQuery?

I have a re-class .fancybox contained in imagemaps.

<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>

      

Then I have an array in jQuery where I want to add the Title attribute. I know it can be added to the HTML, but I need it to be fed by this array of clients, since the imagemaps are generated by the server side CMS which I cannot edit.

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

      

The problem is that on Map2 it starts at the beginning of the array again, rather than continuing in the array like the fourth .fancybox on the page. I assume this because they have different parent elements. Is it possible to take all .fancybox elements, assign headers from an array to them, and update the HTML with jQuery so that all .fancybox classes on the page are assigned from an array so that they appear?

I also tried using the 'area' selector with the same result:

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

      

+3


source to share


2 answers


Since you call index () with no arguments, it returns the index of each element relative to its siblings. Therefore, this index will be "reset" when moving from one element <map>

to another.

You can use the argument index

provided by each () :



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

      

This way the index will keep increasing for each item and won't be reset between maps.

+2


source


You must use index

each()



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

      

+1


source







All Articles