簡體   English   中英

JavaScript 如何使用公共 API 和純 JavaScript 更改輸入值

[英]JavaScript how to change input value using public API and pure JavaScript

誰能向我解釋為什么單擊提交按鈕后無法更新輸入值? 我的目標是寫一個數字,單擊提交按鈕並找到具有該數字的神奇寶貝。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <div class="pokemon"></div> <button id="btn" onclick="testFunc(inputValue)">SUBMIT</button> <input type="text" value="" id="myInput"> <script> const btn = document.getElementById("btn"); const input = document.getElementById("myInput"); let inputValue = input.value; const testFunc = function(a) { const apiData = { url: 'https://pokeapi.co/api/v2/', type: 'pokemon', id: a, } const { url, type, id } = apiData const apiUrl = `${url}${type}/${id}` fetch(apiUrl) .then((data) => { if (data.ok) { return data.json() } throw new Error('Response not ok.'); }) .then(pokemon => generateHtml(pokemon)) .catch(error => console.error('Error:', error)) const generateHtml = (data) => { console.log(data) const html = ` <div class="name">${data.name}</div> <img src=${data.sprites.front_default}> <div class="details"> <span>Height: ${data.height}</span> <span>Weight: ${data.weight}</span> </div> ` const pokemonDiv = document.querySelector('.pokemon') pokemonDiv.innerHTML = html } } </script> </body> </html>

我將不勝感激任何建議。

此致

您需要在testFunc函數內移動inputValue檢索。

const testFunc = function() {
  let inputValue = input.value;
  const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: inputValue,
  }

按鈕的onclick只知道它自己,它不能引用input

 const btn = document.getElementById("btn"); const input = document.getElementById("myInput"); const testFunc = function() { let inputValue = input.value; const apiData = { url: 'https://pokeapi.co/api/v2/', type: 'pokemon', id: inputValue, } const { url, type, id } = apiData const apiUrl = `${url}${type}/${id}` fetch(apiUrl) .then((data) => { if (data.ok) { return data.json() } throw new Error('Response not ok.'); }) .then(pokemon => generateHtml(pokemon)) .catch(error => console.error('Error:', error)) const generateHtml = (data) => { //console.log(data) <-- Slows down the result const html = ` <div class="name">${data.name}</div> <img src=${data.sprites.front_default}> <div class="details"> <span>Height: ${data.height}</span> <span>Weight: ${data.weight}</span> </div> ` const pokemonDiv = document.querySelector('.pokemon') pokemonDiv.innerHTML = html } }
 <div class="pokemon"></div> <button id="btn" onclick="testFunc()">SUBMIT</button> <input type="text" value="25" id="myInput"> <!-- Default to Pikachu -->

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM