Функция Javascript сортирует по индексу, а не по имени файла - PullRequest
0 голосов
/ 18 декабря 2018

У меня есть эта база данных и эта функция сортировки.Сортировка выполняется в HTML-таблицу, которая взяла данные из файла database.json.Проблема в том, что когда он сортирует, он сортирует их по индексу, а не по имени местоположения, как было задано.Например, в этом случае он только обратит первый набор данных с последним.(1,2,3) -> (3,2,1)

Пожалуйста, помогите ...

БАЗА ДАННЫХ

[
    {
        "title": "Great big event",
        "location": "Grand plaza"
    },
    {
        "title": "Cross cultural food tasting",
        "location": "Melius Restaurant",
        "date": "18 December 2018",
        "time": "8 PM",
        "description" : "Food tasting event where you can enjoy a mix of 10 famous cuisines"
    },
    {
        "title": "Small dining event",
        "location": "Cafe Il diroma",
        "date": "10 February 2019",
        "time": "6 AM",
        "description": "The perfect place for casual dinners"
    }
] 

ФУНКЦИЯ СОРТИРОВКИ

location.sort(function(a, b){
    if(a.location < b.location) { return -1; }
    if(a.location > b.location) { return 1; }
    return 0;
})
</script>
<body>
    <div class="show-inline-block">
        <button onclick="location.sort(a,b)" class="button button2">Sort table</button>
    </div>
<div id="result"></div>
</body>

ОБНОВЛЕНИЕ: Сортировка выполняется в таблицу HTML, созданную с данными из database.json

<div class="table-responsive">
  <table class="table table-striped" id="myTable" >
    <thead>
      <tr>
        % for k in displaykeys:
        <th scope="col" style="padding-left:30px">{{k.title()}}</th>
        % end   # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
      </tr>
    </thead>
    <tbody>
      % for i, d in enumerate(displaydata):    # displaydata is expected to be a list of dictionaries
      % link_url = "/events/" + str(i + 1)     # relative url to detailed view
      <tr>
        % for k in displaykeys:     # Go thru the keys in the same order as for the headline row
        <td style="padding-left:30px"><a href="{{link_url}}" alt="See details">{{displaydata[i][k]}}</a></td>
        % end   # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
      </tr>
      % end
    </tbody>
  </table>
</div>

1 Ответ

0 голосов
/ 18 декабря 2018

Ваш код сортировки не является проблемой.Проблема заключается в структуре вашего общего кода.

location является глобальным, а не именем, которое вы должны переопределить.Кроме того, в вашем HTML onclick вы передаете a и b, которые не имеют значений и не определены.

Вам необходимо настроить функцию обратного вызова для события click вашей кнопки и вэту функцию вы можете выполнить сортировку.

См. встроенные комментарии ниже:

// Don't use global names as identifiers. "location" is a global.
let loc = [
    {
        "title": "Great big event",
        "location": "Grand plaza"
    },
    {
        "title": "Cross cultural food tasting",
        "location": "Melius Restaurant",
        "date": "18 December 2018",
        "time": "8 PM",
        "description" : "Food tasting event where you can enjoy a mix of 10 famous cuisines"
    },
    {
        "title": "Small dining event",
        "location": "Cafe Il diroma",
        "date": "10 February 2019",
        "time": "6 AM",
        "description": "The perfect place for casual dinners"
    }
];

// Get your DOM references
let btn = document.querySelector("button");

// Set up event handling in JavaScript, not HTML
btn.addEventListener("click", sort);

// Set up a function that can be called when the button is clicked
function sort(){
  // Do your sort in that function
  loc.sort(function(a, b){
    if(a.location < b.location) { return -1; }
    if(a.location > b.location) { return 1; }
    return 0;
  });
  
  // Show results
  console.log(loc);
}
<div class="show-inline-block">
  <button class="button button2">Sort table</button>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...