首页 \ 问答 \ 创建局部变量以在javascript中跟踪日历上的月份。(Creating a local variable to keep track of months on a calendar in javascript.)

创建局部变量以在javascript中跟踪日历上的月份。(Creating a local variable to keep track of months on a calendar in javascript.)

在这里,我有一个完整的html页面,用于创建日历,复制它以查看它的作用。 我下面有两个按钮可以逐个增加。 我的问题是因为我可以在页面顶部实例化var month= date.getMonth() ,全局变量month只允许我递增1,我怎么能让month设置为局部变量所以我是能够增加到超过1.这是代码:我确信复制粘贴将工作:

下面我发布了我的按钮处理程序以增加月份/减少月份。

<script type="text/javascript"> 

printCalendar(year,month,divDestination);
function printCalendar(year,mth,divDestination){
var currentmonth = mth;
var myOutput=document.getElementById(divDestination)
myOutput.innerHTML=makeCalendar(year,mth)
}
function prevMonth(m){
    m--;
    var currentmonth = m;
    alert(m);
    if(m < 0)
    {
        m = 11;
        year--;
    }

    printCalendar(year,currentmonth,divDestination);
}
function nextMonth(m){
    m++;    
    var currentmonth = m;
    if(m > 11)
    {
        m=0;
        year++;
    }
    printCalendar(year,currentmonth,divDestination);
}
function test(div){
var myOutput=document.getElementById("divCalendar")
myOutput.innerHTML += eventmonth;
}
</script>

<div align="center" id="divCalendar"></div>
<div align="center" id="myButtons">
<input type="button" onclick="test('divCalendar')" value="Say hi" />
<input type="button" onclick="prevMonth(month,'divCalendar')" value="Previous"/>
<input type="button" onclick="nextMonth(month,'divCalendar')" value="Next" />
<input type="button" onclick="printCalendar(year,month,'divCalendar')" value="Reload Calendar" />

下面是我的makeCalendar函数

var myDate = new Date();
    var month = myDate.getMonth();
    var year = myDate.getFullYear();
    var divDestination="divCalendar";

    function leapYear(yr) { 
        if (yr < 1000) yr+=1900
        return((yr%4 == 0) && ((yr%100 == 0) || (yr%400 ==0)))
    }

    function startCol(width, height, color){
        return('<TD WIDTH=' + width + ' HEIGHT=' + height + '>' + '<FONT COLOR="' + color + '">');
    }

    function getHoliday(monthSelected,theday)
    {
        monthSelected = monthSelected + 1
        var holiday = ""
        var HolidayName = new Array (1, 1, "New Year's Day",7, 1, "Canada Day",12, 25, "Christmas Day",12, 26, "Boxing Day", 2,14,"Valentine's Day")
        for(var index = 0; HolidayName.length >= index; index++)
        {   
            if(HolidayName[index] == monthSelected && HolidayName[index+1] == theday)
            {
                holiday = HolidayName[index+2]
            }
        }
        return holiday
    }

    function makeCalendar(yr, mth)
    {
        var monthSelected = mth
        var months    = new Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")
        var days      = new Array(31, leapYear(yr)?29:28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
        var weekDays  = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat")

        var mthSz         = days[mth]
        var mthName       = months[mth]
        var firstDyofMnth = new Date(yr, mth, 1)
        var firstDay      = firstDyofMnth.getDay() + 1
        var numRows       = Math.ceil((mthSz + firstDay-1)/7)
        var mthNameHeight = 50

        var borderWidth   = 2
        var cellSpacing   = 4 
        var cellHeight    = 80 

        var hdrColor      = "midnightblue" 
        var hdrSz         = "+3" 
        var colWidth      = 100 

        var dayCellHeight = 25 
        var dayColor      = "black" 
        var dayCtr        = 1

        // Build the HTML Table 
        var txt = '<CENTER>'
        txt += '<TABLE BORDER=' + borderWidth + ' CELLSPACING=' + cellSpacing + '>' 

        //Show Month Name and Year
        txt += '<TH COLSPAN=7 HEIGHT=' + mthNameHeight + '>' 
        txt += '<FONT COLOR="' + hdrColor + '" SIZE=' + hdrSz + '>' 
        txt += mthName + ' ' + year + '</FONT>' + '</TH>'

        // Show Days of the Week 
        txt += '<TR ALIGN="center" VALIGN="center">'
        for (var dy = 0; dy < 7; ++dy) {
            txt += startCol(colWidth, dayCellHeight, dayColor) + weekDays[dy] + '</FONT></TD>' 
        }
        txt += '</TR>'

        // Show Dates in Calendar
        for (var row=1; row <= numRows; ++row) 
        {
            txt += '<TR ALIGN="right" VALIGN="top">'
            for (var col = 1; col <= 7; ++col) 
            {
                if (((col < firstDay) && (row==1)) || (dayCtr>mthSz))
                    {txt += '<TD BGCOLOR="Gainsboro"><BR></TD>'}
                else
                    {
                        var event = getHoliday(monthSelected, dayCtr)
                        txt += '<TD HEIGHT=' + cellHeight + '><FONT COLOR="' + dayColor + '"> <B>'
                        txt += dayCtr
                        txt += '</B></FONT><BR>' + event + '</TD>'
                        dayCtr++;
                    }       
            }
            txt += '</TR>'
        }
        // close all basic table tags and output txt string
        txt += '</TABLE></CENTER>'  
        return txt
        }

Here I have below a full html page for a calendar creation, copy it over to see what it does. I have two buttons below that can increment month by one. My problem is because I can instantiating var month= date.getMonth() at the top of the page, the global variable month only allows me to increment and decrement by 1, how can I let month be set as a local variable so I am able to increment to more than just 1. Here is the code: I'm sure copy paste will work:

Below I have posted my my button handlers to increase month/decrease month.

<script type="text/javascript"> 

printCalendar(year,month,divDestination);
function printCalendar(year,mth,divDestination){
var currentmonth = mth;
var myOutput=document.getElementById(divDestination)
myOutput.innerHTML=makeCalendar(year,mth)
}
function prevMonth(m){
    m--;
    var currentmonth = m;
    alert(m);
    if(m < 0)
    {
        m = 11;
        year--;
    }

    printCalendar(year,currentmonth,divDestination);
}
function nextMonth(m){
    m++;    
    var currentmonth = m;
    if(m > 11)
    {
        m=0;
        year++;
    }
    printCalendar(year,currentmonth,divDestination);
}
function test(div){
var myOutput=document.getElementById("divCalendar")
myOutput.innerHTML += eventmonth;
}
</script>

<div align="center" id="divCalendar"></div>
<div align="center" id="myButtons">
<input type="button" onclick="test('divCalendar')" value="Say hi" />
<input type="button" onclick="prevMonth(month,'divCalendar')" value="Previous"/>
<input type="button" onclick="nextMonth(month,'divCalendar')" value="Next" />
<input type="button" onclick="printCalendar(year,month,'divCalendar')" value="Reload Calendar" />

Here below is my makeCalendar function

var myDate = new Date();
    var month = myDate.getMonth();
    var year = myDate.getFullYear();
    var divDestination="divCalendar";

    function leapYear(yr) { 
        if (yr < 1000) yr+=1900
        return((yr%4 == 0) && ((yr%100 == 0) || (yr%400 ==0)))
    }

    function startCol(width, height, color){
        return('<TD WIDTH=' + width + ' HEIGHT=' + height + '>' + '<FONT COLOR="' + color + '">');
    }

    function getHoliday(monthSelected,theday)
    {
        monthSelected = monthSelected + 1
        var holiday = ""
        var HolidayName = new Array (1, 1, "New Year's Day",7, 1, "Canada Day",12, 25, "Christmas Day",12, 26, "Boxing Day", 2,14,"Valentine's Day")
        for(var index = 0; HolidayName.length >= index; index++)
        {   
            if(HolidayName[index] == monthSelected && HolidayName[index+1] == theday)
            {
                holiday = HolidayName[index+2]
            }
        }
        return holiday
    }

    function makeCalendar(yr, mth)
    {
        var monthSelected = mth
        var months    = new Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")
        var days      = new Array(31, leapYear(yr)?29:28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
        var weekDays  = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat")

        var mthSz         = days[mth]
        var mthName       = months[mth]
        var firstDyofMnth = new Date(yr, mth, 1)
        var firstDay      = firstDyofMnth.getDay() + 1
        var numRows       = Math.ceil((mthSz + firstDay-1)/7)
        var mthNameHeight = 50

        var borderWidth   = 2
        var cellSpacing   = 4 
        var cellHeight    = 80 

        var hdrColor      = "midnightblue" 
        var hdrSz         = "+3" 
        var colWidth      = 100 

        var dayCellHeight = 25 
        var dayColor      = "black" 
        var dayCtr        = 1

        // Build the HTML Table 
        var txt = '<CENTER>'
        txt += '<TABLE BORDER=' + borderWidth + ' CELLSPACING=' + cellSpacing + '>' 

        //Show Month Name and Year
        txt += '<TH COLSPAN=7 HEIGHT=' + mthNameHeight + '>' 
        txt += '<FONT COLOR="' + hdrColor + '" SIZE=' + hdrSz + '>' 
        txt += mthName + ' ' + year + '</FONT>' + '</TH>'

        // Show Days of the Week 
        txt += '<TR ALIGN="center" VALIGN="center">'
        for (var dy = 0; dy < 7; ++dy) {
            txt += startCol(colWidth, dayCellHeight, dayColor) + weekDays[dy] + '</FONT></TD>' 
        }
        txt += '</TR>'

        // Show Dates in Calendar
        for (var row=1; row <= numRows; ++row) 
        {
            txt += '<TR ALIGN="right" VALIGN="top">'
            for (var col = 1; col <= 7; ++col) 
            {
                if (((col < firstDay) && (row==1)) || (dayCtr>mthSz))
                    {txt += '<TD BGCOLOR="Gainsboro"><BR></TD>'}
                else
                    {
                        var event = getHoliday(monthSelected, dayCtr)
                        txt += '<TD HEIGHT=' + cellHeight + '><FONT COLOR="' + dayColor + '"> <B>'
                        txt += dayCtr
                        txt += '</B></FONT><BR>' + event + '</TD>'
                        dayCtr++;
                    }       
            }
            txt += '</TR>'
        }
        // close all basic table tags and output txt string
        txt += '</TABLE></CENTER>'  
        return txt
        }

原文:https://stackoverflow.com/questions/14883674
更新时间:2022-07-27 10:07

最满意答案

每列存储一个值,否则您无法进行关系查询。 有关数据库规范化的介绍,请参阅此优秀讨论

users

uid
...

followers

uid u_follow
1   2
1   3
2   1
2   3
3   1
3   2
5   2
5   3
5   4

然后:

select u_follow, count(*) as num_followers from followers group by u_follow

如果您想要包含没有关注者的用户,请执行以下操作:

with a as (
  select u_follow, count(*) as num_followers
  from followers group by u_follow
)
select users.uid, coalesce(a.num_followers,0)
from users outer join a on users.uid = a.u_follow

Store one value per column, otherwise you just can't do relational queries. See this excellent discussion for an introduction to database normalization.

users

uid
...

followers

uid u_follow
1   2
1   3
2   1
2   3
3   1
3   2
5   2
5   3
5   4

Then:

select u_follow, count(*) as num_followers from followers group by u_follow

If you want to include users with no followers do something like:

with a as (
  select u_follow, count(*) as num_followers
  from followers group by u_follow
)
select users.uid, coalesce(a.num_followers,0)
from users outer join a on users.uid = a.u_follow

相关问答

更多
  • 您可以使用Postgres中的数组模拟MySQL的find_in_set()函数。 select * from inboxes where '6' = any (string_to_array("to",',')); 请注意, to是保留关键字,因此需要引用"to" 。 通常,您不应将关键字保留为列名(或任何其他标识符) 但是你应该考虑修复你的数据模型。 您的模型违反了第一个正常形式,从长远来看会给您带来更多麻烦。 最大的问题之一是您无法对存储在该字符串值中的值定义任何外键约束,或者您是否可以对数据强 ...
  • SELECT name FROM orders,company WHERE orderID = 1 AND companyID IN (attachedCompanyIDs) attachedCompanyIDs是一个标量值,它被转换为INT ( companyID类型)。 演员只返回数字到第一个非数字(在你的情况下为逗号)。 从而, companyID IN ('1,2,3') ≡ companyID IN (CAST('1,2,3' AS INT)) ≡ companyID ...
  • 尝试这个: SELECT p.* FROM `uc_users` p WHERE EXISTS (SELECT 1 FROM `uc_users` WHERE `id` = 1 AND find_in_set(p.id, following) > 0 ) ORDER BY p.id DESC LIMIT 20; 更改: FIND_IN_SET(p.id,following) > 0 存储分隔列表太糟糕了。 相反,您应该存储每个
  • 函数FIND_IN_SET()的文档: FIND_IN_SET(str,strlist) 如果字符串str位于由N个子字符串组成的字符串列表strlist中,则返回1到N范围内的值。 字符串列表是由以“,”字符分隔的子字符串组成的字符串。 它的第二个参数是一个包含以逗号分隔的值的字符串。 传递给FIND_IN_SET()的值(具有类型SET的列set_col )与此描述匹配。 但是,它的第一个参数应该只是列表中包含的值之一。 a,b不是作为第一个参数传递给FIND_IN_SET()因为它包含值: a和b 。 ...
  • 好吧, FIND_IN_SET将检查用逗号分隔的各个值。 在您的情况下,您应该使用IN子句。 试试这个查询。 $search = "level_whometoteach IN (".$toteach.")"; $this->db->where($search); $query=$this->db->get(); return $result = $query->result(); Well, FIND_IN_SET will check for individual va ...
  • 考虑以下两个WHERE子句: WHERE FIND_IN_SET('value', set_col) > 0 WHERE FIND_IN_SET('value', set_col) 在第一个中,如果sel_col中的任何条目包含value ,则FIND_IN_SET()的返回值将是大于0的某个数字,否则它将为0.换句话说,如果找到该value ,它将返回TRUE ,否则为FALSE 。 第二个WHERE子句将计算为WHERE X ,其中X是1或更大,如果找到value ,或者0,如果找不到value 。 ...
  • IN接受要搜索的列表或参数, FIND_IN_SET接受包含逗号分隔列表的字符串参数: SELECT 1 IN (1, 2, 3, 4) SELECT FIND_IN_SET(1, '1,2,3,4') 如果您尝试将IN应用于以逗号分隔的字符串,它会将其视为单个参数,并将其作为整体匹配: SELECT 1 IN ('1,2,3,4') 当然,字符串'1'不等于字符串'1,2,3,4'因此上面的查询返回false。 IN accepts a list or parameters to search ...
  • 使用IFNULL作为列名称: SELECT * FROM invite WHERE user_id <> 1 AND (FIND_IN_SET(2, IFNULL(invited_friends, 0)) > 0) AND (FIND_IN_SET(2, IFNULL(accepted_invitation, 0)) = 0); 检查SQL小提琴: http ://sqlfiddle.com/#!9/98d95 / 9 Use IFNULL for the colum ...
  • WHERE IN要求在查询中按字面指定值集,而不是包含逗号分隔字符串的单个值。 如果你写: WHERE 6 IN (a.allowed_activity) 它会将a.allowed_activity视为单个值,并将其与6进行比较,而不是将其作为一组多个值进行搜索。 FIND_IN_SET在逗号分隔的字符串中搜索该值。 查看它的另一种方法是IN是一组与OR结合的测试的快捷方式: WHERE x IN (a, b, c, d) 是的缩写 WHERE x = a OR x = b OR x = c OR x ...
  • 每列存储一个值,否则您无法进行关系查询。 有关数据库规范化的介绍,请参阅此优秀讨论 。 users uid ... followers uid u_follow 1 2 1 3 2 1 2 3 3 1 3 2 5 2 5 3 5 4 然后: select u_follow, count(*) as num_followers from followers group by u_follow 如果您想要包含没有关注者的用户,请执行以下操作: with a as ( ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)