0

我试图通过单击下一个和上一个链接在 div 中动态打印下个月和上个月。尽管该值已正确生成,但该值并未打印在<div id="month"></div>. 我要去哪里错了。我在用着$("#month").html(curmonthYear);

<html>
    <head>
        <script type="text/javascript">
            var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

                var cur_dat = new Date();
                var curYear = cur_dat.getFullYear();
                var curMonth = cur_dat.getMonth();
                var curMonthYear = month[cur_dat.getMonth()] + ", " + cur_dat.getFullYear();
            function monthNav(nav) {

                if(nav == 'prev') {

                    var newMonth = cur_dat.getMonth() - 1;
                    var newYear = cur_dat.getFullYear();
                    if(newMonth < 0) {
                        newMonth = 11;
                        newYear -= 1;
                    }

                    cur_dat.setMonth(newMonth);
                    cur_dat.setFullYear(newYear);
                    curMonthYear = month[newMonth] + ", " + newYear;
                    alert(curMonthYear); // gives correct date
                    $("#month").html(curMonthYear); // but doesn't prints here.
                    //alert("Prev");


                } else {

                    var newMonth = cur_dat.getMonth() + 1;
                    var newYear = cur_dat.getFullYear();
                    if(newMonth > 11) {
                        newMonth = 0;
                        newYear += 1;
                    }

                    if(newYear == curYear && newMonth > curMonth) {
                        return false;
                    }
                    cur_dat.setMonth(newMonth);
                    cur_dat.setFullYear(newYear);
                    curMonthYear = month[newMonth] + ", " + newYear;
                    alert(curMonthYear); // gives correct date
                    $("#month").html(curMonthYear); // but doesn't prints.

                }

            }

        </script>
    </head>
    <body>
        <a href="#" onclick="monthNav('prev')">Prev</a>
        <div id="month">abc</div>
        <a href="#" onclick="monthNav('next')">Next</a>
    </body>
</html>
4

3 回答 3

3

如果你在jQuery,你必须在你编码<head>之前将它作为一个库添加到你的库中,例如。<script>

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
于 2013-10-20T04:50:37.700 回答
3

您正在使用jQuery( $) 但未在代码中包含 jquery js。

包括 jquery(来自 cdn 或您自己的本地副本),例如:

<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>

或使用本机 dom 选择器:

document.querySelector("#month").innerHTML = curMonthYear;

于 2013-10-20T04:52:25.170 回答
1
document.getElementById( 'month' ).innerHTML = curMonthYear;
于 2013-10-20T05:08:20.040 回答