I'm a JS n00b, so my apologies for asking something so simple. (It's so simple that the rest of SO is providing more complex answers than I need.) I have a JSON array like this:
var comics = {"spider":"Spiderman", "bat":"Batman", "super":"Superman", "aqua":"Aquaman"};
开发者_如何学PythonAnd I want to access items in that array from another array, like so:
var childhood_heroes = {"fire":"Firefighters", "jordan":"Michael Jordan", "superhero":[comics.super, comics.bat]};
I'm attaching it with jQuery to a div in my HTML with:
$('#which_heroes').click(function() {
$('#jobs').html(childhood_heroes.fire);
$('#sports').html(childhood_heroes.jordan);
$('#supers').html(childhood_heroes.superhero);
});
The first two work when the third is absent. The presence of the third breaks everything. What am I doing wrong?
This
$('body').html(["one","two"]);
Produces
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
So, your issue is that you're passing an array of strings to the jQuery .html()
function, which apparently doesn't handle it too well. Turn it into a string before you pass it, something like
$('#supers').html(childhood_heroes.superhero.join(', '));
should work.
The two valid arguments for .html()
from http://api.jquery.com/html/ are
html( htmlString )
.html( htmlString )
.html( function(index, oldhtml) )
You're accessing an Array where you probably want a String, you can use join() to put all the entries in the superhero array into a string:
$('#supers').html(childhood_heroes.superhero.join(", "));
Make sure comics
is initialized before childhood_heroes
.
And not to nitpick, but neither of the things you defined are JavaScript or JSON arrays. They're only "arrays" in the very loose sense of "associative arrays".
The pair: "super":"Superman"
will cause probs as super
is reserved, so comics.super
will raise an error in IE at least.
Rename it, or use comics["super"]
notation.
精彩评论