jquery: ¿cómo accedo a un elemento de matriz en un objeto jquery?

Heres the problem. I am building a jquery program that lets me create and position divs on a drawing area. I need to keep track of the divs, their location, CSS proterties and other details. So, I am creating an object that contains an array of all these items for each div.

This is the code fragment for creating the object.

var divData= {items: [
{ID: "21", Block: "Block_01", posX : "450", posY : "540" },
{ID: "43", Block: "Block_02", posX : "250", posY : "440" },
{ID: "46", Block: "Block_03", posX : "50", posY : "54" },
{ID: "54", Block: "Block_04", posX : "140", posY : "210" },
{ID: "55", Block: "Block_05", posX : "900", posY : "820" },
{ID: "79", Block: "Block_06", posX : "380", posY : "520" }
]};

And this is the code that I have written to display the contents of the array.

alert ('array length is : ' + divData.items.length);

This statement returns a value of 6 which is correct, Also, I can push data into the array with this statement the alert statement now says 7.

divData.items.push({ID: "266", Block: "Block_01", posX : "450", posY : "540" });

The problem is when I try to display the contents of the array with the following code, nothing happens.

for (var i=0;i<divData.items.length;i++)
{
document.write(divData.items[i] + "<br>");
}       

The output on the screen is this [object Object] seven times.

¿Qué estoy haciendo mal?

Cualquier ayuda será muy apreciada.

Muchas Gracias

Chris

preguntado el 24 de diciembre de 12 a las 21:12

1 Respuestas

The 'items' in your array are objects. You can't output an object on the screen directly. You have to specify which property of the object you are trying to access:

for (var i = 0;i < divData.items.length; i++)
{
  document.write(divData.items[i].ID + "<br/>"); // access the OBJECT's property!
}   

Es posible que desee hacer algo me gusta:

for (var i = 0;i < divData.items.length; i++)
{
  $("#container").append("<div class='positionedDiv' id='" + divData.items[i].ID + "' style='top: " + divData.items[i].posY + "px;left:" + divData.items[i].posX + "px;></div>");
}   

Algo de CSS:

.positionedDiv {
  position: absolute; 
}

Respondido el 24 de diciembre de 12 a las 21:12

Got it. Thanks so much, I just didn't make the obvious connection. Thanks so much. - Chris

Just of interest, how would I delete a row? - Chris

@Chris: If this answers your question, then make sure to upvote the answer and mark it as accepted. :) - johankj

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.