I'm a JQuery Newbie. I'm trying to append an object property( declared in an array form) to an html element like the following
HTML:
<div id="container">
<p>some text </p>
<p>some text </p>
<p>some text </p>
</div>
JQuery Script:
var obj{
property : {'apple', 'orange', 'banana'}
}
for(i=0; i<=2; i++){
$("#container p:e开发者_如何转开发q("+i+")").append(obj.property[i]);
}
and hope to get this:
<p>some text apple</p>
<p>some text orange</p>
<p>some text banana</p>
There are no appending shown at all, though my Firebug console shows no error report.
What am I doing wrong? Also, is there any way to replace the for loop with .each(), if it's a better practice?
Thank you
Your list of properties isn't correctly formed. A numerically indexed list literal is formed using square brackets, not curly brackets.
The code you posted should be giving you a syntax error. If it's not, it's possible that it's simply not getting executed at all.
Here's a fixed up version:
var obj = {
property : ['apple', 'orange', 'banana']
}
for(i=0; i<=2; i++){
$("#container p:eq("+i+")").append(obj.property[i]);
}
As stated in another answer, obj
should be defined as such:
var obj = {
property : ['apple', 'orange', 'banana']
}
The for loop will work, but it seems better practice to use .each()
, if for no other reason just because you don't have to hard-code the values -- if you use for
, then if you ever change the number of properties, you'll have to go update that loop too. Here is how I would do it:
$("#container > p").each(function(i) { $(this).append(obj.property[i]); });
精彩评论