我想做一个功能,用户每天只能领取一次硬币。
我使用了 .split
函数,以便它仅比较日期,因为 Date()
仅比较日期和时间。但是,我遇到了这个 JavaScript 错误:
Uncaught TypeError (intermediate value).split is not a function
有谁知道如何解决这个问题吗?我尝试了很多方法。错误仍然存在。
这是我的代码:
$(document).ready(function () {
if (new Date(model[0].lastClaimedDate).split(' ')[0] < new Date().split(' ')[0]) {
document.getElementById('btnAddCoins').disabled = false;
}
else {
document.getElementById('btnAddCoins').disabled = true;
}
})
最佳答案
问题
var date = new Date();
var claimedDate = new Date(date.setDate(date.getDate()-1)) ;
var todaysDate = new Date()
// converting toString and splitting up
claimedDate = claimedDate.toDateString().split(" ");
todaysDate = new Date().toDateString().split(" ");
// result date with array of Day, MonthName, Date and Year
console.log("claimed date", claimedDate)
console.log("todays date", todaysDate)
`var d = new Date();` // Todays date
如果你执行 d.split("")
::会给你一个错误 d.split 不是一个函数
你可以通过 d.toDateString().split("")
//给你一个数组 ["Fri", "Sep", "28", "2018"]`
使用上面的内容您可以检查之前的日期
您可以查看toDateString method ,现在数组由日、月、日期和年组成。因此您可以检查之前的日期,并且可以禁用或启用该按钮。
更好的解决方案
无需转换为String和split,直接查看两个日期即可,查看解决方案
解决方案
$(document).ready(function () {
var date = new Date();
var lastClaimedDate = new Date(date.setDate(date.getDate() - 1 ));
var currentDate = new Date();
if(lastClaimedDate < currentDate){
$("#btnAddCoins").prop("disabled", true)
}else{
$("#btnAddCoins").prop("disabled", false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddCoins">Add Coins</button>
关于Javascript Uncaught TypeError : . split 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547876/