$('#all_locations').append(""); $('#all_locations').append("City "); $.each(data, function(i, item){ $('#all_locations').append(""); $('#all_locations').append(""+item.city+" "); $('#all_locations').append(" "); } $('#all_locations').append("
");
Sortie obtenue en utilisant alert($('#all_locations').html());
City Seattle Chicago
Ce code se déclenche lorsque l’appel ajax est terminé. Des idées pourquoi le fait-il?
Supposons que cette variable de données soit l’object JSON valide.
Malgré l’abstraction proposée par jQuery, vous utilisez des éléments du DOM, et non des balises de la source HTML.
jQuery('
est un raccourci pour jQuery(document.createElement('table'))
.
Vous devez append les lignes de votre table à la table et non au conteneur (de même, les cellules doivent être ajoutées aux lignes).
Il est .append()
de créer une chaîne de votre code HTML à append et à exécuter un appel .append()
sur cette chaîne:
//declare our output variable var output = 'City '; //iterate through data $.each(data, function(i, item){ //add to output variable output += '' + item.city + ' '; } //append the output to the DOM $('#all_locations').append(output);
Il est assez courant de voir des personnes placer des éléments dans un tableau et rejoindre ce tableau pour l’ajout:
//declare our output variable (array) var output = ['City ']; //iterate through data $.each(data, function(i, item){ //add to output variable output.push('' + item.city + ' '); } //append the output to the DOM after joining it together into a ssortingng $('#all_locations').append(output.join(''));
Ajoutez un id
à la balise pour résoudre ce problème. Ajoutez ensuite le sous-élément à cet id
au lieu de l’élément parent.
$(function(){ for(var lvl=0;lvl<5;lvl++) { $("#tblId tbody").append(" "); for(var fchr=0;fchr<3;fchr++) $("#tblId tbody #"+lvl).append("Val"+lvl+fchr+" "); } alert($('#tblId').html()); });
Exemple en cours, voir ici: http://jsfiddle.net/WHscf/1/
Au lieu de le faire de cette façon, essayez quelque chose comme ceci:
var table = $(""); if (table){ table.append($("").append($("").text("City"))); $.each(data, function(i, item){ table.append($(" ").append($("").text(item.city))); }); table.appendTo($("#all_locations")); }
Voici une autre façon qui se rapproche de la façon dont vous le faites actuellement:
$("#all_locations""#all_locations").append("City "); $.each(data, function(i, item){ $('#all_locations').append(""); $('#all_locations').append(""" " + item.city + " "td> "); $('#all_locations').append(""}); } $("#all_locations tr").wrapAll("
");