从可变数量的元素中检索REL内容并存储在数组中

时间:2014-02-04 18:53:22

标签: jquery arrays area rel

我一直在努力研究如何做到这一点,但是我的jQuery / JavaScript水平太多了,所以我无法解决我出错的地方。

我只是尝试在可变数量的区域标记中创建所有REL属性的数组:

<map name="Map">
    <area shape="rect" coords="45,13,125,107" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-aft-stateroom.jpg" href="/img/yachts/layouts/lrg/horizon-56-aft-stateroom.JPG" alt="Aft Stateroom" title="Aft Stateroom">
    <area shape="rect" coords="310,37,366,83" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-vip-cabin-2.JPG" href="/img/yachts/layouts/lrg/horizon-56-vip-cabin-2.JPG" alt="VIP Cabin" title="VIP Cabin">
    <area shape="rect" coords="126,19,207,99" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-salon.jpg" href="/img/yachts/layouts/lrg/horizon-56-salon.jpg" alt="Saloon" title="Saloon">
    <area shape="rect" coords="207,12,284,52" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-port-cabin.jpg" href="/img/yachts/layouts/lrg/horizon-56-port-cabin.jpg" alt="VIP Cabin" title="Port Cabin">
    <area shape="rect" coords="223,68,285,116" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-starbord-cabin.jpg" href="/img/yachts/layouts/lrg/horizon-56-starbord-cabin.jpg" alt="VIP Cabin" title="Starboard Cabin">
    <area shape="rect" coords="4,16,37,107" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-platform.jpg" href="/img/yachts/layouts/lrg/horizon-56-platform.jpg" alt="VIP Cabin" title="Swim Platform">
    <area shape="rect" coords="366,28,406,96"  class="lightbox" rel="/img/yachts/layouts/sml/Horizon-56-bowpad.jpg" href="/img/yachts/layouts/lrg/horizon-56-bowpad.JPG" alt="Bow" title="Bow of Horizon 56">
  </map>

我的最终目标是将其提供给一个简单的jQuery预加载器以预加载这些图像,但是一旦我可以构建阵列,我就可以处理这一点!

提前感谢您提供的任何帮助!

鲍勃

1 个答案:

答案 0 :(得分:1)

演示:http://jsfiddle.net/CFGb7/1/

// create array for storing rels
var rels = [];
// loop through each `area` element
// you could adjust this selector to be more specific if you like
$('area').each(function(i, el){
    // push onto the array, each element's `rel` attribute
    rels.push($(el).attr('rel'));
})
// check what the array looks like now :)
console.log(rels)
// should log to console...
// ["/img/yachts/layouts/sml/horizon-56-aft-stateroom.jpg", "/img/yachts/layouts/sml/horizon-56-vip-cabin-2.JPG", "/img/yachts/layouts/sml/horizon-56-salon.jpg", "/img/yachts/layouts/sml/horizon-56-port-cabin.jpg", "/img/yachts/layouts/sml/horizon-56-starbord-cabin.jpg", "/img/yachts/layouts/sml/horizon-56-platform.jpg", "/img/yachts/layouts/sml/Horizon-56-bowpad.jpg"]