开发者

Adding elements into associative array in javascript

I'm trying to add elements into an Associative Array, which is colors = [] I want it to have the ["id":selected_color] but my browser keeps crashing (an infinite loop somewhere?)

I'm not sure if I'm adding the elements into the array correctly.

What is happening is that I'm clicking on a span element, which has its ID value set to a hexcode 开发者_JAVA百科value, and I'm trying to capture that value and associate it with the selected._color

<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">

var selected_color = "";
var colors = [];

$(document).ready(function() {
    $(".color_cell").click(function(){
        // ADD MY COLOR TO SELECTED COLOR'S ASSOCIATIVE ARRAY       
        colors[$(this).attr("id")] = selected_color;
        console.log($(this).attr("id"));
        $(this).css({'background-color':'white'});
        $(this).unbind('click');
        updateDisplay(colors);
        alert("hi");
    });

    $(".btnColor").click(function(){
         // MAKE SELECTED COLOR BE ME
        alert("hey");
        selected_color = $(this).attr("id");
    }); // end button handler
}); // end ready()

function updateDisplay(colors) {
    jQuery.each(colors, function(key, value) {
        //it seems to crash here...
        $("#storage_display").html("var "+$("#storage_display").html()+" " +value);
    });
};
</script>


You're defining colors as an array instead of an object.

You just need to initialize it properly:

 var colors = {}; // or new Object();

Additional suggestion... there's really no need for the jQuery.each here. Iterating over an associative array like this (let's not argue the semantics of whether you can actually call this an associative array) looks like this:

function updateColors(colors)
{
    for (var key in colors)
    {
        $("#storage_display").html("var "+$("#storage_display").html()+" " +colors[key]);
    }
}


Why don't you try just some normal javascript instead of

colors[$(this).attr("id")] = selected_color; 

try using

colors.push(selected_color);

and instead of your jquery loop, try using

for(var i = 0; i < colors.length; i++) {
    $('#storage_display').html('whatever your trying to do here use colors[i]');
}

I dont understand what you're trying to do in the loop but assuming it did work, the html will be something like 'var var var var var var hexcode hexcode hexcode hexcode hexcode'


Apart from everything that was mentioned before ID attributes must begin with a letter A-Z or a-z . That might crash your browser.

Also if you are only storing colors in your array why not use just a normal array? (as James suggests)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜