简体   繁体   中英

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

On load I create a map, the key is an anker-element and the value the offset of that anker. Unfortunately I cannot read out the val correctly, it always returns the value of the last key. What is 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, which you're using for a map here only support string keys (like objects in most other languages).

If you want an actual map should use a Map object instead if you'd like to use an object key - but those only work in new browsers, you can ( polyfill it 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, you can use the element's ID as a key and give them IDs. Or, you can avoid this altogether and save the data on the objects rather than in a map:

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

$('a').click( function(e) {
    e.preventDefault();
    alert($(this).data("anker");
});

Fiddle

You should only use data attributes for presentation properties and binding, but this seems to be appropriate and is the case here.

The property of the object in javascript is always a String. So when you try to set a map with an object as a key, this object is converted to string type. As the result you have only ankers object has only one key [object Object] .

Instead consider to give an ids to anchors and use something like this:

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

$('a').click(function (e) {
    e.preventDefault();
    $('.val').val(ankers[this.id]);
});

Demo: http://jsfiddle.net/1c4h17ma/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM