虽然我确实使用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>
价格和货币未定义。
我是否有办法只保留其中一个变量给我的函数,同时保留已经存在的值?
道歉必须是一个非常基本的问题。我刚刚接触到这一点,我显然在路上误解了一些东西。
答案 0 :(得分:0)
好的,这是更新的答案。如您所见,如果变量是在代码的全局范围内声明的,则日期选择器函数可以访问它。我认为之前没有用,因为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>
答案 1 :(得分:0)
如果您在以下地区宣布价格和货币:
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
然后你需要做的是使用&#34;这个&#34;用于访问价格和货币值的关键字。就像下面的例子一样。 您可能还需要查看此链接以获取更多信息:https://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, this.price, this.currency )
}
}
);
});