在我对jQuery的新手理解中,这段代码应该将日落时间输入到span div中。但它不起作用。有什么提示吗?
HTML
<div id="sunsetbox">Sunset tonight at<span></span></div>
JQuery的
$(function(){
var month = getMonth()+1;
var day = getDate();
var todaysdate = (month+'/'+day+'/');
var sunsettimes = [10/1,"7:19",10/2,"7:17",10/3,"7:15"];
var index = sunsettimes.indexOf(todaysdate);
var indexsunset = index + 1;
var displaysunsettime = sunsettimes.slice(indexsunset);
$("#sunsetbox span").html(displaysunsettime);
});
答案 0 :(得分:1)
尝试
$(function() {
var date = new Date();
//need to use a date object
var month = date.getMonth() + 1;
var day = date.getDate();
//there is no / after day
var todaysdate = month + '/' + day;
var sunsettimes = ['10/1', "7:19", '10/2', "7:17", '10/3', "7:15"];
var index = sunsettimes.indexOf(todaysdate);
var indexsunset = index + 1;
//need to get the value at index indexsunset
var displaysunsettime = sunsettimes[indexsunset];
$("#sunsetbox span").html(displaysunsettime);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sunsetbox">Sunset tonight at <span></span>
</div>
&#13;
答案 1 :(得分:1)
代码中有很多错误,这段代码应该做你想要的。
$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var todaysdate = month+'/'+day;
var sunsettimes = ["10/1","7:19","10/2","7:17","10/3","7:15"];
var index = sunsettimes.indexOf(todaysdate);
var indexsunset = index + 1;
var displaysunsettime = sunsettimes[indexsunset];
$("#sunsetbox span").html(displaysunsettime);
});
答案 2 :(得分:0)
日落时间的日期需要是字符串。 (“10/1”,而不是10/1)现在,你正在10&amp; 1,所以你的索引var的值被设置为-1(未找到)。
答案 3 :(得分:0)
我认为这一行:
var sunsettimes = [10/1,"7:19",10/2,"7:17",10/3,"7:15"];
是主要问题,因为您输入的日期被解释为操作(对于第一个,10除以1)。 长宁行:
var sunsettimes = ['10/1',"7:19",'10/2',"7:17",'10/3',"7:15"];
所以使用日期作为字符串应该做的伎俩。
另外,正如你所说,你是新手,我会允许自己给你一些建议/知识。您使用的系统(包含键和值并排的列表)似乎很奇怪,因为已经有一些事情在Javascript中完美地解决了这个问题。那些东西就是物体。
这就是你如何使用它们:
$(function() {
var date = new Date();
//need to use a date object
var month = date.getMonth() + 1;
var day = date.getDate();
var todaysdate = month + '/' + day;
var sunsettimes = {
'10/1': "7:19",
'10/2': "7:17",
'10/3': "7:15"
};
//need to get the value at index indexsunset
var displaysunsettime = sunsettimes[todaysdate];
$("#sunsetbox span").html(displaysunsettime);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sunsetbox">Sunset tonight at <span></span>
</div>
对象允许您将值与键相关联,并且它们将返回与您传递的键相关联的值。
我希望我足够清楚