所以我正在使用 HTML 和 JS 开发股票市场模拟器。我有一个 API here获取当前股票价格。这是我的 HTML http://pastebin.com/ymcGKtin抱歉,pastebin 不太擅长格式化 SO。但是在添加股票函数中,我试图将提交的表单 stock
推送到数组 stocks
。但是,我在尝试弄清楚如何获取提交的表单 stock
并将其推送到数组时遇到了问题。如果我能得到一些关于如何做到这一点的指示,它就会被应用。具体来说,我希望获得有关将属性 stock
推送到数组 Stocks
的帮助。想法?
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback){
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult){
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult){
console.error(jsonResult);
}
Market.makeRequest = function () {
//Abort any open requests
if (this.xhr) { this.xhr.abort(); }
//Start a new request
this.xhr = $.ajax({
data: { symbol: this.symbol },
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock(){
alert("derp");
// Stocks.push(ele.getAttribute)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit = "addStock()">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
</body>
</html>
最佳答案
对于 JQuery,您可以使用 find
在表单对象上(onsubmit
处理程序中的 this
):
...
function addStock(form){
var value = $(form).find('input[name="stock"]').val();
alert(value);
Stocks.push(value);
//prevents a submit of the form
return false;
}
</SCRIPT>
<form onsubmit = "return addStock(this);">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
...
关于javascript - 使用 HTML 中的输入来运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36509592/