我想创建一个web应用程序,显示API中的多个客户,当我单击某个客户时,将显示该客户的其他信息.

到目前为止,我已经获取了作为数组的API数据,为数组中的每个项目创建了一个列表和一个按钮.现在,当我按下一个客户按钮时,我想再次调用我的API,但使用id作为参数来访问有关该客户的特定信息.

然而,要做到这一点,我需要从我按下的按钮中保存"id"变量,我不知道如何实现它.

这就是我的应用程序看起来的样子(苗条)

<script>
  import { onMount } from 'svelte'
    
  let customers = []

  onMount(() => {
    fetch('https://europe-west3-gcp-task-346814.cloudfunctions.net/customer-function-1/getCustomer')
      .then(response => response.json())
      .then(result => customers = result)
  })
    
  function handleClick() {
        
  }
    
</script>


{#each customers as customer (customer.id)}
<h2>
    <button on:click={() => handleClick()}>
    {customer.name}
  </button>
</h2>   

<p>
    id: {customer.id}
</p>
<hr>
{/each}

请注意,我对JS和HTML比较陌生.

推荐答案

您可以执行下面的代码.基本上,您需要将从迭代中获得的客户传递到h和leClick函数.

<script>
  import { onMount } from 'svelte'
    
  let customers = []

  onMount(() => {
    fetch('https://europe-west3-gcp-task-346814.cloudfunctions.net/customer-function-1/getCustomer')
      .then(response => response.json())
      .then(result => customers = result)
  })
    
  function h和leClick(customer) {
        // here you have access to the customer id by doing customer.id
        console.log(customer)
  }
    
</script>


{#each customers as customer (customer.id)}
<h2>
    <button on:click={() => h和leClick(customer)}>
    {customer.name}
  </button>
</h2>   

<p>
    id: {customer.id}
</p>
<hr>
{/each}

代码改变了:

<button on:click={() => h和leClick(customer)}>

function h和leClick(customer) {
     console.log(customer)
}

Javascript相关问答推荐

D3多线图显示1线而不是3线

通过在页面上滚动来移动滚动条

在React中获取数据后,如何避免不必要的组件闪现1秒?

我开始使用/url?q=使用Cheerio

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

我怎么在JS里连续加2个骰子的和呢?

JS:XML insertBefore插入元素

类构造函数不能在没有用With Router包装的情况下调用

第二次更新文本输入字段后,Reaction崩溃

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

如何在Bootstrap中减少网格系统中单个div的宽度

使用NextJS+MongoDB+Prisma ORM获取无效请求正文,无法发布错误

为什么我的按钮没有从&q;1更改为&q;X&q;?

当从其他文件创建类实例时,为什么工作线程不工作?

不同表的条件API端点Reaction-redux

Reaction useState和useLoaderData的组合使用引发无限循环错误

计算对象数组中属性的滚动增量

在Press Reaction本机和EXPO av上播放单个文件

带元素数组的Mongo聚合

我如何让我的弹力球在JavaScript和HTML画布中相互碰撞后改变 colored颜色 ?