我有来自w3school的这段代码并根据我的需要进行了修改,我想出了这段代码
<div id="city"></div>
<p id="demo"></p>
<div id="province"></div>
<script>
(function () {
var xmlhttp = new XMLHttpRequest();
var url = "http://getpark.net/city/read";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<div class='row'>" +
"<div class='large-12 columns'>" +
"<label>City</label>" +
"<select id='select' name='city' onchange='change()'>";
for(i = 0; i < arr.length; i++) {
out += "<option value='" +
arr[i].cityId +
"'>" +
arr[i].cityName +
"</option>";
}
out += "</select>" +
"</div>" +
"</div>";
document.getElementById("city").innerHTML = out;
}
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
})();
但为什么onchange in change()函数没有成功呢?我从w3school看到它。 http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange 谢谢。
答案 0 :(得分:1)
您的更改功能应该在全局范围内。您只需在script-tag之后直接移动函数声明。
<script>
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
(function () {
[..]