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
Post a Comment