I have a link with a 'rel' attribute:
&开发者_如何学Golt;a href="#" rel="music">Click</a>
<p></p>
I have a variable containing JSON:
var myStyle = {
"music": { "band": "Beatles", "type": "Rock"},
"movie": { "title" "Shrek", "type": "Kids"}
};
I want to use jQuery to get values from JSON according to the 'rel' attribute:
$('a').click(function() {
var whatLink = $('a').attr('rel');
$('p').text(myStyle.whatLink.band);
});
I see that the value of "style" is "music" but the result of clicking the link is
TypeError: Cannot read property 'band' of undefined
Is it even possible?
Try
$('a').click(function() {
var whatLink = $('a').attr('rel');
$('p').text(myStyle[whatLink].band);
});
When accessing properties using variables, dot operator does not work and you have to use dictionary/array operator.
If you are using...
$('a').click(function() {
var whatLink = $('a').attr('rel');
$('p').text(myStyle[whatLink].band);
});
...whatLink
is always gonna give you the rel
value of the last (or first, can't remember) a
in your page. To really check the rel
value of the link you just clicked, use this
instead of 'a'
in the selector inside the event. Like so...
$('a').click(function() {
var whatLink = $(this).attr('rel');
$('p').text(myStyle[whatLink].band);
});
TypeError: Cannot read property 'band' of undefined
This is because the whatLink
property does not exist of myStyle
, therefore returning undefined
, which of course has no band
property.
Use bracket notation...
$('a').click(function() {
var whatLink = $('a').attr('rel');
$('p').text(myStyle[whatLink].band);
});
...otherwise whatLink
is taken literally.
精彩评论