css 使用JSON搜索结果中的条目生成URL

vatpfxk5  于 2023-04-23  发布在  其他
关注(0)|答案(1)|浏览(89)

下面的简单HTML模板是通过JavaScript搜索栏由卡片填充的。现在所有的卡片都显示相同的固定URL:"https://www.url.com/aaa。我需要将每个url中的aaa替换为正在搜索的JSON file中的url元素。
这是我的工作代码:https://jsfiddle.net/25tmakbu/1/

const userCardTemplate = document.querySelector("[data-user-template]")
const userCardContainer = document.querySelector("[data-user-cards-container]")
const searchInput = document.querySelector("[data-search]")

let users = []

searchInput.addEventListener("input", e => {

  const value = e.target.value.toLowerCase()
  const xy = value.split(' ')

  users.forEach(user => {

    if (parseFloat(value.length) < 3) {
      user.element.classList.toggle("hide", true)
    } else {
      var distance = Math.sqrt(
        Math.pow(parseFloat(xy[0]) - parseFloat(user.x), 2) +
        Math.pow(parseFloat(xy[1]) - parseFloat(user.y), 2))
      const isVisible =
        user.name.toLowerCase().includes(value) || distance <= 10
      user.element.classList.toggle("hide", !isVisible)
    }
  })
})

fetch("https://ucc.ar/_clusters/test.json")
  .then(res => res.json())
  .then(data => {
    users = data.map(user => {
      const card = userCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      header.textContent = user.name
      body.textContent = user.company
      card.classList.add('hide');
      userCardContainer.append(card)
      return {
        name: user.name,
        x: user.x,
        y: user.y,
        element: card
      }
    })
  })
.search-wrapper {
  display: flex;
  flex-direction: column;
  gap: .25rem;
}

input {
  width: 80%;
  margin: 0 auto;
  display: block;
  padding: 12px 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 18px;
  background-color: #ffffff;
}

.user-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: .25rem;
  margin-top: 1rem;
}

.card {
  border: 1px solid black;
  background-color: white;
  padding: .5rem;
  text-align: center;
}

.card>.header {
  margin-bottom: .25rem;
}

.card>.body {
  font-size: .8rem;
  color: #777;
  font-weight: bold;
}

.hide {
  display: none;
}
<div class="search-wrapper">
  <input type="search" id="search" placeholder="Search the catalogue" data-search>
</div>
<div class="user-cards" data-user-cards-container></div>
<template data-user-template>
      <div class="card">
        <a href="https://www.url.com/aaa">
          <div class="header" data-header></div>
        </a>
        <div class="body" data-body></div>
      </div>
    </template>
6rqinv9w

6rqinv9w1#

由于您要复制<a href="https://www.url.com/aaa">标记沿着卡片模板的其余部分,因此需要覆盖href值。card.querySelector("a").setAttribute("href", "https://www.url.com/" + user.url);应该可以完成此任务。

相关问题