javascript - JS - How to get the correct val of a map? -



javascript - JS - How to get the correct val of a map? -

on load create map, key anker-element , value offset of anker. unfortunately cannot read out val correctly, returns value of lastly key. wrong?

js fiddle

html

<a>anker</a><a>anker</a><a>anker</a>

js

var ankers = {}; $('a').each(function(){ var pos = $(this).offset().left; ankers[$(this)] = pos; }); $('a').click( function(e) { e.preventdefault(); alert(ankers[$(this)]); });

javascript objects, you're using map here back upwards string keys (like objects in other languages).

if want actual map should utilize map object instead if you'd utilize object key - work in new browsers, can (polyfill though):

var ankers = new map(); $('a').each(function(){ var pos = $(this).offset().left; ankers.set($(this), pos); }); $('a').click( function(e) { e.preventdefault(); alert(ankers.get($(this)); });

fiddle (based on dfsq's)

alternatively, can utilize element's id key , give them ids. or, can avoid altogether , save info on objects rather in map:

$('a').each(function(){ $(this).data("anker", $(this).offset().left); }); $('a').click( function(e) { e.preventdefault(); alert($(this).data("anker"); });

fiddle

you should utilize info attributes presentation properties , binding, seems appropriate , case here.

javascript jquery html

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -