未捕获的TypeError:无法设置属性' className'在控制台上出现null错误

时间:2017-06-02 16:24:50

标签: javascript brackets

我在尝试设置代码时遇到了麻烦。当您输入艺术家并按下按钮时,它应该提供所有歌曲

JavaScript文件:

/**
* Uses AJAX to query an internet data source for zip codes
* @param {string} zipId The element id that has the zip code
*/
function Music(music) {
// First get the zip code from the HTML textbox
var yourmusic = document.getElementById(music).value;
// Now make a HTTP request
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
    if (this.readyState === 4) {
        // We got a response from the server!
        if(this.status === 200) {
            // The request was successful!
            displayMusic(this.responseText);
        } else if (this.status === 404){
            // No postal code found
            displayMusic('{ "songs" : "none" }');
        } else {
            console.log("We have a problem: " + this.status);
        }
    } else {
        // Waiting for a response...
    }
};
// Notice how the URL is appended with the zip code
var url = " https://api.mixcloud.com/discover/funk/";
httpRequest.open("GET", url, true);
httpRequest.send();
}
/**
* Displays the zip code place given the JSON data
 * @param {string} data JSON data representing place for given zip 
code
 */
 function displayMusic(data){
 var music = JSON.parse(data);
 if(music.songs === "none") {
    document.getElementById("").className = "alert alert-warning";
    document.getElementById("").innerHTML = "The songs are" + music;
} else {
    document.getElementById("music").className = "alert alert-success";
    document.getElementById("music").innerHTML ="there are no songs for this             artist"
}
}

HTML文件:

<!DOCTYPE html>
<html>
 <head>
 <title>Songs</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="ajaxfunctions.js"></script>
</head>
<body>
<div class="container">
  <h2>Songs </h2>
  <br/>
  <p>Try entering an artist to find their songs</p>
  <div>
    <div id="musicbox" class="control-group">
      <label for="songs">artistr</label>
      <input type="text" name="songs" id="songs" placeholder="Type an artist to their songs" />
    </div>
  </div>
  <br />
  <div>
    <button class='btn btn-success btn-large' onclick="Music('songs')">Find Songs</button>
  </div>
  <br />
  <div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

这些行中的选择器document.getElementById("")

document.getElementById("").className = "alert alert-warning";
document.getElementById("").innerHTML = "The songs are" + music;

将始终返回null!第一行导致错误未捕获TypeError: Cannot set property 'className' of null。很可能你不应该这样做。您需要删除这两行并重新考虑您的逻辑。