createElement 不起作用

createElement does not work

本文关键字:不起作用 createElement      更新时间:2023-09-26

我的代码有什么问题..? 当我调用此函数时,带有带有 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);
}

要专注于您的麻烦部分: 这适用于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>