在javascript中返回Nan值?

时间:2019-02-27 08:28:09

标签: javascript php

我正在尝试通过javascript获取选定月份中选定年份的天数。但这给了我NaN值。我应该怎么做才能解决这个问题?谢谢。

<script>
   function myFunction() {
   var month =parseInt(document.getElementById('month'));
   var year = parseInt(document.getElementById('year'));
   var d = new Date(year, month);
   var n = d.getDate();
   document.getElementById("show").innerHTML = n;
}
</script>

<form>
    <label>Select Year</label>
    <select name="year" required="" id='year'>
        <option value=""></option>
        <?php 
            $curr_year = date('Y');
            $next_year = $curr_year+3;
            for($year = $curr_year; $year<=$next_year; $year++){ ?>
                <option value="<?php echo $year ;?>"> <?php echo $year 
            ;?></option>
        <?php   } ?>
    </select>
    <label>Select Month</label>
    <select name="month" id="month" required="" onchange="myFunction()">
        <option></option>
        <?php
            for($i = 1 ; $i <= 12; $i++){ ?>
                <option value='<?php echo date("F",strtotime(date("Y")."-".$i."-01")); ?>'><?php  echo date("F",strtotime(date("Y")."-".$i."-01"));?></option>
            <?php } ?>
    </select>

    <div class="show" id="show">
        <h1>Hello world....</h1>
    </div>

2 个答案:

答案 0 :(得分:3)

您刚刚获得该元素。下面将获取元素的值。

var month = parseInt(document.getElementById('month').value);

答案 1 :(得分:3)

函数new Date()错误,选择需要进入.value

 function myFunction() {
   var month = document.getElementById('month').value;
   var year = document.getElementById('year').value;
   var d = new Date(year,month,0);
   document.getElementById("show").innerHTML = d.getDate();
}
<form>
    <label>Select Year</label>
    <select name="year" required="" id='year'>
        <option></option>
        <option value="2015">2015</option>
        <option value="2016">2016</option>
        <option value="2017">2017</option>
        <option value="2018">2018</option>
    </select>
    <label>Select Month</label>
    <select name="month" id="month" required="" onchange="myFunction()">  
        <option></option>      
        <option value="01">1</option>
        <option value="02">2</option>
        <option value="03">3</option>
        <option value="04">4</option>
    </select>

    <div class="show" id="show">
        <h1>Hello world....</h1>
    </div>

我不知道您为什么要获取日期,因为date默认为1(不带参数)