开发者

jquery map - assign the return value as a key of the receiving object

开发者 https://www.devze.com 2023-03-17 03:10 出处:网络
I have: <img class=\"images\" src=\"src1\"> <img class=\"images\" src=\"src2\"> <img class=\"images\" src=\"src3\">

I have:

    <img class="images" src="src1">
    <img class="images" src="src2">
    <img class="images" src="src3">
    <img class="images" src="src4">

var pictures = $(".images").map(function(){
    return $(this).attr("src");
})

The code above creates a new pictures array. Can you think of an efficient way to create a new pictures object using the jQuery map function. I would like to do somethin开发者_C百科g like:

var pictures[key] = $(".images").map(function(){
    var key = $(this).attr("src");
    return key;
})

... directly assign the return value as a key to the pictures object. is there a way?


Can't you just iterate the collection?

var picObj = {};
$(".images").each(function() {
    picObj[$(this).attr("src")] = '...';
});

(demo - will print to the console)


I don't understand exactly what you are looking for but you could do something like this:

var pictures = [];

    $(".images").each(function(){
    var src = $(this).attr("src");
    var img = $('<img>', { src: src});
    pictures.push(img)

})

and pictures is an array of image objects

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号