Reputation: 183
This code is reading the first letter of the arrays name, but I want it to read the first object in that array. It's supposed to read an elements array attribute (which it does) then access the first thing in that array. This is my first time working with arrays so this may be a very silly question :)
Thanks heaps.
//array of strategies
//leads
var leads = new Array();
leads[0] = "Test 1";
leads[1] = "Test 2";
leads[2] = "Test 3";
$("button").click(function () {
//get category
var currentCat = $(this).attr("array");
$("#danWell h1").text($(this).attr('id')); //don't worry about this line
$("#danWellContent").text(currentCat[0]);
})
Upvotes: 0
Views: 81
Reputation: 707158
I'm guessing your question is that you have a string that you retrieved from an attribute and you want to access a variable in your javascript with that name. That is generally done by using the object[varName]
where varName
is a javascript variable and this lets you access a property on an object of the name help in that variable.
If the variable you want to access is a global variable, then you can access it via string by indexing off the window
object because all global variables are properties of the window
object:
var currentCat = $(this).attr("array");
var item = window[currentCat][0];
If the variable you want to access is not a global variable, then you need to make it a property on some known object so you can use this same technique.
var myObject = {};
myObject.leads = [];
myObject.leads[0] = "Test 1";
myObject.leads[1] = "Test 2";
myObject.leads[2] = "Test 3";
var currentCat = $(this).attr("array");
var item = myObject[currentCat][0];
FYI, the recommend way to store custom attributes in your HTML is to prefix the custom property with "data-"
and then you can use jQuery's .data()
to retrieve the custom attribute and you will also be compatible with the HTML5 specification for custom attributes.
<div data-array="leads">
var currentCat = $(this).data("array");
Upvotes: 1
Reputation: 10489
It looks like you want to store an array as one of your element's attributes. I recommend that you use .data()
instead of attributes to read and write your array values. This prevents you from adding superfluous attributes, and allows you to retrieve your data with the right type.
To store an array (where $ele
refers to your jQuery element):
var array = [];
array[0] = "Test";
array[1] = "Test";
$ele.data("array", array);
To retrieve the array:
var array = $ele.data("array");
If you store your array as a data-array
attribute of your element, the .data()
call above works exactly the same.
Upvotes: 1