如何获取HTML用户输入并传递给JavaScript函数查询股票行情数据?
核心问题修正点
- 重复ID冲突:HTML中
<p id="symbol"></p>和股票代码输入框的id都是symbol,getElementById会优先获取到无输入值的p标签,导致取不到用户输入的股票代码,直接删掉这个无用的p标签即可。 - 传参错误:按钮
onclick中直接传入了DOM元素对象,没有取.value属性,导致api函数拿到的是元素而非输入值。 - 函数作用域问题:你使用了
type="module"加载JS,模块内的函数默认是私有作用域,不会挂载到window全局,内联onclick事件访问不到api函数,需要手动把api挂载到window对象上。 - 页面加载时直接调用api逻辑错误:原JS代码在页面刚加载就读取输入值,此时用户还未填写内容,这行无效调用可以直接删掉,改成点击按钮时再读取输入值。
- HTML结构错误:
<p>API</p>写在了<html>标签外,属于非法结构,要挪到body内;所有label的for属性都错误写为name,要对应输入框的id才能实现点击label聚焦输入框的效果。 - 日期输入优化:可以把日期输入框的type改成
date,避免用户输入格式错误,浏览器会自动返回标准的YYYY-MM-DD格式值。
修正后的JavaScript代码
import yahooFinance from 'yahoo-finance2'; async function api(symbol, start, end, val) { const query = String(symbol); const queryOptions = { period1: new Date(start), period2: new Date(end), interval: String(val) }; try { let result = await yahooFinance.historical(query, queryOptions); let resultWithSymbol = result.map((item) => ({ ...item, symbol: query })); console.log(resultWithSymbol); return resultWithSymbol; } catch (err) { console.error('查询失败:', err); } }; // 把api挂载到全局,让内联onclick可以访问到 window.api = api;
修正后的HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="module" src="../dist/bundle.js"></script> <title>股票行情查询</title> </head> <body> <p>API</p> <div class="symbol"> <label for="symbol">Symbol (4 characters):</label> <input type="text" id="symbol" name="symbol" required minlength="4" maxlength="4" size="10" placeholder="Exemplo: TSLA"> </div> <div class="interval"> <label for="interval">Interval: (1d, 1wk or 1mo):</label> <input type="text" id="interval" name="interval" required minlength="2" maxlength="3" size="10" placeholder="Exemplo: 1d"> </div> <div class="period1"> <label for="period1">Start Date:</label> <input type="date" id="period1" name="period1" required> </div> <div class="period2"> <label for="period2">End Date:</label> <input type="date" id="period2" name="period2" required> </div> <div class="button"> <input type="button" name="buttonExecute" value="Execute" onclick="api( document.getElementById('symbol').value, document.getElementById('period1').value, document.getElementById('period2').value, document.getElementById('interval').value )"> </div> </body> </html>
内容的提问来源于stack exchange,提问作者user139442
相关产品推荐
相关产品推荐

