将变量发送到其他函数

时间:2018-03-14 09:57:54

标签: javascript html

我正在尝试使用fetch创建一个简单的网页来显示一些用户(我将它们显示为卡片列表)。此外,每个用户都有一个按钮,该按钮导航到另一个页面,我想在其中显示用户的帖子(另一个关于帖子的提取)。 问题是,我应该知道用户的ID,我按下按钮以显示他的帖子。但我怎么能得到这个身份呢?

以下是显示用户卡列表的提取代码:

function getUsers() {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then((res) => res.json())
    .then((data) => {
      let output = '<h2 class="mb-4">Users</h2>';
      data.forEach(function(user) {
        output += `
          <div class ="card" style="width:18rem;">
            <div class ="card-body">
              <h5 class ="card-title">Name: ${user.name}</h5>
              <p class ="card-text">Email: ${user.email}</p>
              <input type="button" id="${user.id}"  value="Show posts" onClick="showpost(this.id)">
            </div>
          </div>
        `;
      });
      document.getElementById('output').innerHTML = output;
    })
}

1 个答案:

答案 0 :(得分:0)

修改下面的一行

<input type="button" id="${user.id}"  value="Show posts" onClick="showpost(this.id)">

<input type="button" id="${user.id}"  value="Show posts" onClick="showpost(${user.id})">

现在你的功能showpost应该看起来像

function showpost(userId){
    alert(userId); // Here you get the ID of the user you want to display the posts
}

通过扩展功能来显示帖子。

相关问题