为脚本标记src属性赋值时发生JavaScript错误

时间:2018-01-12 05:04:05

标签: javascript html

我试图通过使用JavaScript在src中添加一个单词,从另一个div元素中获取该单词。运行它会导致以下错误:

  

无法设置null的属性'src'   这是我的代码:

<html><head></head><body>
<div id='content'></div>
<script>
function handleResponse(response) {
  var post_number  = Object.keys(response.items).length; //number of posts
  for (i=0; i<post_number; i++) { 
    document.getElementById("content").innerHTML += "<div class='posts'><h1>" + response.items[i].title + "</h1>" + response.items[i].content + '</div>';
      
  }
}
</script>
<div id='myImg'>Lists</div>
<script id='demo' src=""></script>
<script>
var x = document.getElementById("myImg").innerHTML;
var y= document.getElementById("demo"); y.src="https://www.googleapis.com/blogger/v3/blogs/5039479718685240371/posts?labels="+x+"&callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA";
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

试试这个:

<script>
    var x = document.getElementById("myImg").innerHTML;
    var s = document.createElement( 'script' );
    s.setAttribute('src', "https://www.googleapis.com/blogger/v3/blogs/5039479718685240371/posts?labels=" + x + "&callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA");
    document.body.appendChild(s);
</script>