Passing JSON array values as JQuery selectors
I'm trying to pass JSON array values into my javascript file and use the values as selectors to call methods on corresponding html divs.
for example:
function clickEvents(items) {
for (var r = 0; r < items.length; r++) {
var开发者_StackOverflow中文版 omega = items[r].id +;
$(omega).click(function() {
alert('Thanks for adding item number #' + omega ' to your cart!');
});
}
where my JSON looks like this:
{
"Items" : [{
"header: "apple",
"id": 5000
}, {
"header": "banana",
"id":5001
}, {
"header": "pear",
"id": 5002
}]
}
unfortunately, its not working properly. I can't seem to get the selectors to match up. Does anyone know the proper syntax for this type of approach or have ideas for other approaches?
when i do this, it works:
function clickEvents(items) {
$('#5001').click(function() {
alert('hi');
});
}
Two things.
First, you can't start an ID with a number. http://www.w3.org/TR/html4/types.html#type-id
Second, you need to concatenate the #
in the selector if you are selecting using ID attribute.
Here's an example: http://jsfiddle.net/3BBtU/
function clickEvents(items) {
for (var r = 0; r < items.length; r++) {
// removed the stray "+" at the end
var omega = items[r].id;
// If you wanted to add an attribute to each element, do it here.
$('#' + omega).attr('someAttribute', 'some value');
// Wrap handler assignment in a closure, passing "omega" in so that
// when it fires, it is referencing the correct value of "omega"
(function(o) {
// concatenate "#" to the ID for a proper ID selector
$('#' + o).click(function() {
// You were missing the second + operator in this concatenation
alert('Thanks for adding item number #' + o + ' to your cart!');
});
})(omega);
}
}
// Modify IDs so that they do not start with a number
var obj = {
"Items" : [{
"header": "apple",
"id": "d5000"
}, {
"header": "banana",
"id": "d5001"
}, {
"header": "pear",
"id": "d5002"
}]
};
// call the clickEvents() passing in the Items from the obj variable
clickEvents(obj.Items);
EDIT:
- Added an example
- Corrected a mistake where I had
functions
instead ofvar
. - Corrected one more issue. I wrapped the handler assignment in a closure because the
omega
variable was being used inside the handler in the concatenation in.alert()
, which means that it was referencing the latest value update ofomega
when a click fired it.
What exactly is going wrong? You're missing a quotation mark after the last "id" in your sample, but maybe it's just a typo...(?)
You have to use something like: $("#"+omega)
.
You are asking for an id, isn't it!?
function clickEvents(items) {
for (var r = 0; r < items.length; r++) {
var omega = items[r].id;
$("#"+omega).click(function() {
alert('Thanks for adding item number #' + omega ' to your cart!');
});
}
In fact th $() function in this case thake a string the is a validCSS selector.
精彩评论