[英]passing variables to function with jquery
盡管我確實使用PHP,但是我是javascript新手。
我在href的onclick事件上使用javascript / jquery傳遞變量時遇到問題。
我正在從遠程URL提取json數據,每個請求都需要3個參數。
日期,價格和貨幣。
我有一個構建URL的功能,如下所示:
function getIndexData(date, price, currency){
ajaxURL = "/data/"+date+"/"+price+"/"+currency+"";
}
這可以很好地工作並構建我需要的URL。
但是,我在頁面上有一個jQuery datepicker,可以將日期更改為所需的日期,如下所示:
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
即使先前已設置價格和貨幣,現在也未定義它們。
我的onclick事件存在相同的問題-如果我嘗試使用以下方式發送價格或貨幣:
<a href="javascript:void(0);" onclick="getIndexData('date','price','currency')">NET</a></span>
價格和貨幣未定義。
有什么辦法可以僅將一個變量發送到函數中,同時保留已經存在的值?
很抱歉,這是一個非常基本的問題。 我對此還很陌生,很顯然我在此過程中誤解了一些東西。
好的,所以這是更新的答案。 如您所見,如果在代碼的全局范圍中聲明了變量,那么日期選擇器函數將可以訪問它。 我認為它以前沒有用,因為html是錯誤的。 我刪除了所有html,只包含了日期選擇器,如果在瀏覽器中對其進行測試,您會看到在控制台中價格,貨幣變量在日期選擇器的onSelect函數中可用,您還可以在其中執行函數getIndexData 。 我已經將該函數分配給了一個變量,這樣您就可以使用變量getIndexData來使用該函數。
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="col-sm-5 index-grid">
<span class="grid-label">Price</span>
<span class="btn btn-grid"><a href="javascript:void(0);" onclick="getIndexData(indexDate, indexCurrency ,indexPrice);">CLOSE</a></span>
<span class="btn btn-grid"><a href="javascript:void(0);" onclick="getIndexData(indexDate, indexCurrency ,indexPrice);">RETURN</a></span>
<span class="btn btn-grid"><a href="javascript:void(0);" onclick="getIndexData(indexDate, indexCurrency ,indexPrice);">NET</a></span>
</div>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
<script>
var ajaxURL;
var indexDate = "2017-08-20"
var indexPrice = "closeprice";
var indexCurrency = "EUR";
var getIndexData = function (indexDate, indexCurrency, indexPrice) {
ajaxURL = "/data/" + indexDate + "/" + indexPrice + "/" + indexCurrency + "";
alert(ajaxURL);
}
$(document).ready(function() {
$(function() {
$("#datepicker").datepicker({
dateFormat: 'yymmdd',
onSelect: function(date) {
console.log(date);
console.log(indexPrice);
console.log(indexCurrency);
console.log(getIndexData);
}
});
});
});
</script>
如果您在以下之外聲明了價格和貨幣:
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
然后,您需要使用“ this”關鍵字來訪問價格和貨幣值。 就像下面的例子一樣。 您可能還需要檢查此鏈接以獲取更多信息: https : //javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, this.price, this.currency )
}
}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.