createElement不起作用

时间:2013-11-17 16:17:35

标签: javascript

我的代码有什么问题..?当我调用此函数时,带有img的锚标记的div不会在区域区域中弹出

function addLink(){

  if(localStorage.getItem('howManyLinks') >= 1){
    localStorage.setItem('howManyLinks', Number(localStorage.getItem('howManyLinks')) + 1);
  }
  else{
    localStorage.setItem('howManyLinks', '1');
  }

  var howManyLinks = localStorage.getItem('howManyLinks');

  var myNewLink = document.getElementById("link");
    localStorage.setItem('link'+howManyLinks, myNewLink.value);

  var myNewIcon = document.getElementById("icon");
    localStorage.setItem('icon'+howManyLinks, myNewIcon.value);

/* below here is where i have trubble */

  var div = document.createElement('div');
  var img = document.createElement('img');
  var a = document.createElement('a');

  img.setAttribute('src','icon'+howManyLinks);
  a.setAttribute('href','link'+howManyLinks);

  section.appendChild(div);
  div.appendChild(a);
  a.appendChild(img);
}

1 个答案:

答案 0 :(得分:0)

专注于你的麻烦部分:这适用于Firefox 25.0 / Linux:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <section id="section">
    </section>
    <script type="text/javascript">
        var div = document.createElement('div');
        var img = document.createElement('img');
        var a = document.createElement('a');
        var section = document.getElementById("section");

        img.setAttribute('src', 'dummyImg2.jpg');
        a.setAttribute('href', 'http://www.example.com');

        section.appendChild(div);
        div.appendChild(a);
        a.appendChild(img);
    </script>
</body>
</html>