1
我试图创建一个switch语句来根据用户选择的数字和字母顺序对表的不同元素进行排序。但是,当我尝试引用排序函数的字段questions.id时,它说它是未定义的?另外,如果我没有定义任何内容并尝试按第一个字段(ID)进行排序,它会在1之前编号126?这里是我到目前为止的代码:在case语句中排序表元素时遇到的问题
$('#sort').on('click', sort);
function sort(){
//Clear all existing rows, so that additional queries do not pile up on top
$("#questions tbody tr").remove();
//Get the JSON data from our HTML and convert it to a JavaScript object
//In the real world, this data will likely be retrieved from the server via an AJAX request
var questions = [
{
"id":1,
"q_category_id":0,
"q_text":"Which of the following is regarded as the real founder of portugese power in India",
"q_options_1":"Pedro Cabral",
"q_options_2":"Almeida",
"q_options_3":"Vasco da Gama",
"q_options_4":"Alfonso de Albuquerque",
"q_correct_option":4,
"q_difficulty_level":2,
"q_date_added":"2013-06-10T04:00:00.000Z"
}
];
var sortquery = $('#sortquestions').val();
switch (sortquery){
case 'Ascending ID':
console.log(sortquery);
questions.id.sort()
break;
case 'Descending ID':
console.log(sortquery);
break;
case 'Ascending Alphabetical':
console.log(sortquery);
questions.q_text.sort();
break;
case 'Descending Alphabetical':
console.log(sortquery);
break;
case 'Ascending Difficulty':
console.log(sortquery);
break;
case 'Descending Difficulty':
console.log(sortquery);
break;
}
//Loop through the list array and create a table row for each item.
$.each(questions, function(i, question) {
var tblRow = '<tr>' +
'<td>' + question.id + '</td>' +
'<td>' + question.q_text + '</td>' +
'<td>' + question.q_options_1 + '</td>' +
'<td>' + question.q_options_2 + '</td>' +
'<td>' + question.q_options_3 + '</td>' +
'<td>' + question.q_options_4 + '</td>' +
'<td>' + question.q_correct_option + '</td>' +
'<td>' + question.q_difficulty_level + '</td>' +
'</tr>'
//Add our table row to the 'questions' <table>
$(tblRow).appendTo('#questions tbody');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="sort" value="sort" />
<select id="sortquestions">
<option>Ascending ID</option>
<option>Descending ID</option>
<option>Ascending Alphabetical</option>
<option>Descending Alphabetical</option>
<option>Ascending Difficulty</option>
<option>Descending Difficulty</option>
</select>
<table id="questions">
<tbody></tbody>
</table>
对不起,已经澄清了,也错过了在代码编辑。 – user3052485
我们是否也可以看到“问题”对象的内容是什么? – dave
添加了一个来自问题的对象示例。 – user3052485