foo.substr给出“不是函数”错误

时间:2013-07-18 23:29:04

标签: javascript jquery

我正在使用Jquery的datepicker插件(工作正常)。然后我需要从选择的日期中提取“星期几”。

使用foo.substring(0,3)分配datepicker('getDate')的前三个字符时,我得到:TypeError foo.substr is not a function

$(function () {
    $("#textDatepicker").datepicker();
});

function selectedDay() {
    var foo = $("#textDatepicker").datepicker('getDate');

    //IF USED.... alert(foo);
    //retuens (for example)..... 
    //"Thu Jul 18 00:00:00 GMT-0400 (Eastern Standard Time)"

    var weekday = foo.substr(0, 3)
    document.getElementById("dayofweek").innerHTML = "The day of the week selected is: " + weekday;
}

<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="https://jquery-blog-js.googlecode.com/files/SetCase.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
</head>
<body>
Select Date:&nbsp;<input type="text" id="textDatepicker" onchange="selectedDay();">
<br><br>
<span id="dayofweek">Selected day of week replaces this</span>
</body>

我还粘贴在:jsfiddle

任何帮助将不胜感激..提前致谢...

5 个答案:

答案 0 :(得分:6)

var foo = $("#textDatepicker").datepicker('getDate');

返回Date对象,而不是字符串,并且没有方法substr()

FIDDLE

你可以通过删除那个难看的内联事件处理程序并执行以下操作来解决它:

$("#textDatepicker").datepicker({
    onSelect: function() {
        var date = $(this).datepicker('getDate');
        var day  = $.datepicker.formatDate('DD', date);
        $('#dayofweek').html(day);
    }
});

FIDDLE

答案 1 :(得分:6)

使用

var weekday = foo.toString().substr(0, 3);

DEMO.

答案 2 :(得分:1)

$("#textDatepicker").datepicker('getDate');

是一个对象。您不能使用substr。

获取对象的子字符串

答案 3 :(得分:0)

foo.substr(0,3)是罪魁祸首。它返回一个日期对象,您可以在日期对象上执行substr。 您可以使用下面的代码解决问题

function selectedDay() {
    var foo = $("#textDatepicker").datepicker('getDate');

    //IF USED.... alert(foo);
    //retuens (for example)..... 
    //"Thu Jul 18 00:00:00 GMT-0400 (Eastern Standard Time)"

    var weekday = foo.getDay();
    document.getElementById("dayofweek").innerHTML = "The day of the week selected is: " + weekday;
}

function selectedDay() { var foo = $("#textDatepicker").datepicker('getDate'); //IF USED.... alert(foo); //retuens (for example)..... //"Thu Jul 18 00:00:00 GMT-0400 (Eastern Standard Time)" var weekday = foo.getDay(); document.getElementById("dayofweek").innerHTML = "The day of the week selected is: " + weekday; }

答案 4 :(得分:0)

在调用toString();之前调用subString();方法 像foo.toString().subString(start,length); 为我工作