Save variable value

I have a problem, I cannot save the value on the page.

My js:

var count = 0;

switch (index) {
case 0:
    count = count - 5;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
case 1:
    count = count + 2;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
case 2:
    count = count + 5;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
}

My html:

<div id="point">
    <p></p>
</div>

How can I save the value?

+4
source share
2 answers

It works, see my jsFiddle

var index = 0; // for demonstration, change that value

var count = 0;

switch (index) {
case 0:
    count = count - 5;
    $('#point p').text(count);
    break;
case 1:
    count = count + 2;
    $('#point p').text(count);
    break;
case 2:
    count = count + 5;
    $('#point p').text(count);
    break;
}

Note. The string $('#point p').text(count);will always be the same in all cases, so you might want to put it after the switch case.

Also, I replaced your string: document.getElementById("point").getElementsByTagName('p')[0].innerText = count;with $('#point p').text(count)to use jQuery. Hope this helps you get started.

+1
source

innerText, . innerHTML, .
jsFiddle demo, , , .


, :

var count = 0;
switch (index) {
    case 0:
        count -= 5;
    break;
    case 1:
        count += 2;
    break;
    case 2:
        count += 5;
    break;
}
// Only once, after the switch. If you want another target for the value,
// all you have to do is change this line, instead of every case.
document.getElementById("point").getElementsByTagName('p')[0].innerHTML = count;

jQuery. JS . jQuery, :

$('#point').find('p')
0

Source: https://habr.com/ru/post/1533495/


All Articles