简体   繁体   中英

Appending to an element in JQuery

I have set up an array of elements containing the alphabet and am trying to append each value as a hyperlink using jquery. I can see my values in the array, but on my page they are showing up as undefined. Can someone shed a little light? thanks.

<p id="alphabet"><a href="#" class="alphaChar"></a></p>
<script>
   var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",     "Q", "R", "S", "T", "U", "W", "X","Y","Z"];
   $.each(alph, function(index, value){
   $("a .alphaChar").append().html( "<a href='"#"' class='alphaClass'>  " +  alph.val + "</a>" );
});
</script>

a number of problems,

Use value instead of alph.val,

your selector was wrong, (You were looking for children with class alphachar)

$("a.alphaChar")

and your .append().html(..) was wrong -you can chain functions in JQuery, so what you were actually doing was "Append nothing, and THEN set the HTML of the entire element to ...".

$("a.alphaChar").append( < HTML GOES HERE > );

See this fiddle http://jsfiddle.net/jFIT/wW5CZ/

var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "W", "X", "Y", "Z"];

$.each(alph, function (index, value) {
    console.log(value);
    $("a.alphaChar").append("<a href='\"#\"' class='alphaClass'>  " + value + "</a>");
});

Rather than appending it a loop, build your entire DOM element and append at the end:

var html = ""
$.each(alph, function(index, value){
    html += "<a href='#' class='alphaChar'>  " +  value + "</a>" );
});

$("a.alphaChar").append(html);

There is some syntax error in your code I think you want to do this :

JavaScript:

var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",   "P", "Q", "R", "S", "T", "U", "W", "X","Y","Z"];
$.each(alph, function(index, value){
   $("a.alphaChar").append("<a href='#' class='alphaClass'>  " +  value + "</a>" );
});

Use this code

var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T", "U", "W", "X","Y","Z"];
for (var i=0; i < alph.length; i++) {
    $("a .alphaChar").append($("<a href='#' class='alphaClass'>" +  alph[i] + "</a>" ));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM