使用按钮功能进行图像分类

时间:2018-11-28 05:15:31

标签: javascript html css

我有两个按钮功能 排序最喜欢和最新 这只是模拟,可以硬编码

如何将按钮与功能链接。

这是其中之一的源代码。

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta charset="UTF-8" />
</head>
<body>
<button onclick="function1">Sort Most Like</button>
<button onclick="function2">Sort Most Recent</button>
    <div id="app"></div>
    <script src="src/index.js">
    </script>
</body>
</html>

<script>



const imgArr = [
  { src: "https://unsplash.it/300/225?image=0", Recent: "24/1/2018", Likes: 6 },
  { src: "https://unsplash.it/300/225?image=0", Recent: "24/3/2018", Likes: 2 },
  { src: "https://unsplash.it/300/225?image=0", Recent: "25/1/2018", Likes: 3 },
  { src: "https://unsplash.it/300/225?image=0", Recent: "24/2/2018", Likes: 1 },
];

const html = imgArr.sort((a, b) => {
return a.Likes + b.Likes
}).map(imageItem => {
  return `<figure class="einzel"><img alt="Mitglieder" src=${
    imageItem.src
  } style="width: 315px; height: 250px;">
      <figcaption>Name: ${imageItem.Name}<br>
        <span>Likes: ${imageItem.Likes}</span></figcaption>
  </figure>`;
});


document.getElementById("app").innerHTML = html;



</script>

1 个答案:

答案 0 :(得分:0)

下面的代码包含按喜欢按升序对条目进行排序的功能。

const imgArr = [{
    src: "https://unsplash.it/300/225?image=0",
    Recent: "24/1/2018",
    Likes: 6
  },
  {
    src: "https://unsplash.it/300/225?image=0",
    Recent: "24/3/2018",
    Likes: 2
  },
  {
    src: "https://unsplash.it/300/225?image=0",
    Recent: "25/1/2018",
    Likes: 3
  },
  {
    src: "https://unsplash.it/300/225?image=0",
    Recent: "24/2/2018",
    Likes: 1
  },
];

/* Gemeric function to display array content on screen */
const init = (ar) => ar.map(el => {
  return `<figure class="einzel"><img alt="Mitglieder" src=${
    el.src
  } style="width: 315px; height: 250px;">
      <figcaption>Recent: ${el.Recent}<br>
        <span>Likes: ${el.Likes}</span></figcaption>
  </figure>`;
});

const sortByLikes = (a, b) => {
  if (a.Likes === b.Likes) {
    return 0;
  }
  return a.Likes > b.Likes ? 1 : -1;
};

/* Generate array sorted by number of likes ascending */
const function1 = () => {
  document.getElementById("app").innerHTML = init([...imgArr].sort(sortByLikes));
}

document.getElementById("app").innerHTML = init(imgArr);
<button onclick="function1()">Sort Most Like</button>
<button onclick="function2">Sort Most Recent</button>
<div id="app"></div>