我试图在getTopics()
函数中返回主题的位置以及主题。例如,返回"乐器"也会返回整数0,然后可以在getFaqs()
函数中使用。返回"编程语言"也会返回整数1,依此类推。我不明白为什么这个功能不起作用,因为我已经包含了参数topic_id(整数)和主题(文本)。
的index.html:
function getTopics() {
$.getJSON("topics.php", function(result) {
$("#topic-container").html("");
$.each(result, function(topic_id, topic){
$("<div>", {id: topic_id , text: topic, onclick: "getFaqs(this.id, $(this).text())"}).appendTo($("#topic-container"));//pass topic_pos
});
});
return false;
}
topics.php:
<?php
header('Content-Type: application/json; charset=utf-8');
$topics = array("Musical instruments", "Programming languages", "Varieties of pizza");
?>
答案 0 :(得分:1)
只需在数组上使用standard for
loop:
var topic, topic_id;
for (topic_id = 0; topic_id < result.length; topic_id++) {
topic = result[topic_id];
$("<div>", {id: topic_id , text: topic, onclick: "getFaqs(this.id, $(this).text())"}).appendTo($("#topic-container"));//pass topic_pos
}