我无法向<p>显示javascript变量?

时间:2016-05-28 13:19:17

标签: javascript

我不知道我的代码中有什么问题我用我的一些代码参考并完成了这个但是我不能在一个字形图中显示变量?

这是我在脚本上的代码:

<script type="text/javascript">
    var myId = document.getElementById('myId').value; // 
    var scope = 'global';

    function testScope() { 

    var scope = 'local';

        function innerFunc() {  
        return scope;           
        }                           

    return innerFunc(); 
    }

    var answer = testScope(); 

    myId.innerHTML = answer;
</script>

on html

<p id="myId"><!-- no variable displayed --></p>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

使用document.getElementById('myId')代替document.getElementById('myId').value。因为<p>元素没有value属性

function checkFunctionScope() {
  var myId = document.getElementById('myId');
  var scope = 'global';

  function testScope() {

    var scope = 'local';

    function innerFunc() {
      return scope;
    }

    return innerFunc();
  }

  var answer = testScope();

  myId.innerHTML = answer;
}

window.onload = checkFunctionScope;
<p id="myId">
  <!-- no variable displayed -->
</p>