如何增加JS或jQuery中的数字?

时间:2017-01-20 06:50:38

标签: javascript jquery

我需要每24小时在同一个HTML ID中增加几个不同的数字。 因此,如果一个数字为1而另一个数字为20,无论数字是多少,都必须加1。

正如您所看到的,我只需要一种方法来将HTML ID中的任何数字增加+1,而不是将数字更改为1。 这是我的代码

<p id="pColor">
    Flower are on day <span>(<span id="datePlus">1</span>)</span>
</p>
<p id="pColor">
    Fruiting Plants are on day <span>(<span id="datePlus">20</span>)</span>
</p> 

JS

function theDate() {
    var initialDate = new Date(2017, 0, 19); // Dec 1st 2012
    var now = Date.now();
    var difference = now - initialDate;
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    var daysSince = Math.floor(difference / millisecondsPerDay);
    console.log(daysSince);
    function dateUpdate() {
        if(daysSince >=1) {
            console.log("True");

            // THIS IS WHERE I WANT CODE TO GO

        } else {
            console.log("false");
        }
    }
}

theDate();

4 个答案:

答案 0 :(得分:1)

首先你需要上课,而不是id。

在html页面中,id不能重复。

使用class增加每个元素的值。

isFibonacci(13);
function isFibonacci( $testedNumber, $a = 1, $b = 1 )
{
    if( $testedNumber == 0 || $testedNumber == 1 )
        return true;//returning true for 0 and 1 right away.
    $nextFib = $a + $b;//getting the next number in the sequence
    if( $nextFib > $testedNumber )
        return false;//if we have passed the tested number, it's not in the sequence
    else if( $nextFib == $testedNumber )
        return true;//if we have a perfect match, the tested number is in the sequence
    else
        isFibonacci( $testedNumber, $b, $nextFib );//otherwise, get the next fibonacci number and repeat.
} 

当此代码运行时,它会在每个元素中将值增加一个。

答案 1 :(得分:0)

您可以为此循环添加+1 for jquery

&#13;
&#13;
for(var i = 1;i<7;i++)
{
  $("#demo").append(i+"</br>");//just for testing
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="demo"></p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

首先,将id="datePlus"更改为class="datePlus"

然后使用此功能:

function theDate() {
    var initialDate = new Date(2017, 0, 19);
    var now = Date.now();
    var difference = now - initialDate;
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    var daysSince = Math.floor(difference / millisecondsPerDay);

    if(daysSince > 0) {
        $(".datePlus").each(function(){
            var $this = $(this);
            var number = parseInt($this.text());
            number = isNaN(number)? daysSince: number + daysSince;
            $this.text(number);
        });
    }
}

答案 3 :(得分:0)

首先,更改

元素之一的id pColor,因为ID必须是唯一标识符。例如:

<p id="datePlus">Flower are on day <span >(<span id="datePlus">1</span>)     </span></p>
  <p id="datePlus">Fruiting Plants are on day <span >(<span id="datePlus2">20</span>)</span></p> 

然后,您可以使用指定的元素:

 var number1 = $( "span#datePlus" ).text();
 number1 = parseInt(number1);
 var number2 = $("span#datePlus2").text();
 number2 = parseInt(number2);
 number1++;
 number2++;
 $("span#datePlus").text(number1);
 $("span#datePlus2").text(number2);