1

I am utterly new to JavaScript and am trying to self-learn a few things - so be gentle.

I am trying to set a variable using document.getElementById(' ').innerHTML but I can't get it to work - I just get "undefined" returned when I try to use this variable.

All of the examples I have seen says that this should work, but it isn't and I'm at my wits' end. Any help will be greatly appreciated.

This is the code...

<script>
var str = document.getElementById('str').innerHTML;

function calc()
{
  if(document.getElementById('checkbox').checked)
     document.getElementById('str').innerHTML = str ;     
  else
     document.getElementById('str').innerHTML='unchecked';
}

</script>

Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>

My ultimate aim is to add a number to the variable "str" using another variable; so something like...

var str = document.getElementById('str').innerHTML;
var add = 2
function calc()
{
  if(document.getElementById('checkbox').checked)
     document.getElementById('str').innerHTML = str + add;     
  else
     document.getElementById('str').innerHTML='unchecked';
}

I'm aware that I probably need to parse the str variable as an integer for this, but I've stumbled before I've even got that far.

Please help.

4

4 回答 4

3

的值str是在页面加载时(以及元素存在之前)确定的。我相信你想要它在里面calc

function calc()
{
  var span = document.getElementById('str');
  var str = span.innerHTML;
  var add = 2;
  if(document.getElementById('checkbox').checked)
     span.innerHTML = str + add;     
  else
     span.innerHTML = 'unchecked';
}
于 2013-09-13T17:29:28.123 回答
1

问题是您的跨度在脚本下方,实际上 str 不在那里。这是一个有效的示例http://jsfiddle.net/krasimir/2C25E/

<script>
function calc() {
    var str = document.getElementById('str').innerHTML;
    var add = 2;
    if(document.getElementById('checkbox').checked)
        document.getElementById('str').innerHTML = parseInt(str) + add;     
    else
        document.getElementById('str').innerHTML='unchecked';
}
</script>

Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>

此外,您应该使用 parseInt 来确保您获得的是数字而不是字符串。

于 2013-09-13T17:29:58.823 回答
0

如果您已将脚本包含在<head>标签中,这将适用于您。

function calc() {

var str = document.getElementById('str').innerHTML;
//more code
于 2013-09-13T17:33:38.807 回答
0

试试这个,一个工作版本和一点优化:

var str = document.getElementById('str');
var chk = document.getElementById('checkbox');
var add = 2
    function calc() {
        chk.checked ? str.innerHTML = parseInt(str.innerHTML) + add : str.innerHTML = 6;
    }
chk.onchange = function () {
    calc();
};

演示在这里

于 2013-09-13T17:35:14.813 回答