简体   繁体   中英

How can I get this javascript var to work across HTML pages?

Page 1:

<html>
<head>
</head>
<body>
    <input type="checkbox" class="checkbox" name="item" value="X">Value X<br>
    <input type="checkbox" class="checkbox" name="item" value="Y">Value Y<br>
    <script type='text/javascript'>
        var score = 0;
        $('.checkbox').click (function(){
          var thisCheck = $(this);

          if ( thisCheck.is(':checked') ) {
            score = score + 1;
          }
        });
        sessionStorage.score = score;
    </script>
    <button type="button" onclick="window.location.href='page2.html'">Continue</button>
</body>
</html>

Page 2:

<html>
<head>
</head>
<body>
    <script type='text/javascript'>
    var score = sessionStorage.getItem('score');
    document.write(score);
    </script>
</body>
</html>

Page 2 always prints null. How can I fix this?
(If both checkboxes were selected, we need page 2 to print 2, for example)

Thanks!

NB I know that there is an easy solution to this by having a form action write to an asp file and then reading that, but I can't create new files on this system.

First neither of your checkboxes actually have a class of 'checkbox' so that jquery event will never fire even if you check one of the checkboxes.

Also, you are declaring the variable as thisCheck but trying to access it using thischeck (notice the lower-case c). Javacript is case-sensitive so 'thischeck' is never being assigned a value.

您的会话设置不正确,需要执行此操作,需要sessionStorage.setItem("score", score)

You need to set sessionStorage value on each click:

var score = 0;
$('.checkbox').click (function() {
  if (this.checked) {
      score = score + 1;
  }
  sessionStorage.score = score;
});
sessionStorage.score = score;

Note, that if probably want to deduct 1, if checkbox is unchecked, in this case try this code:

var score = 0;
sessionStorage.score = score;

$('.checkbox').click (function() {
    score = score + (this.checked ? 1 : -1);
    sessionStorage.score = score;
});

And btw, you need to add class="checkbox" to inputs.

I found the solution. score was being parsed as something other than an Int for whatever reason.

Using score = parseInt(score) + 1; solved the problem.

Thanks to everyone who submitted answers! We got there in the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM