所以我想得到一个JSON对象的列表,然后通过fori循环来循环它的元素,创建了 <li>
和 <a>
一切都很顺利,除了当我试图在每次迭代中添加一个onclick函数。我试图将json对象传递给onclick函数,但是所有的标签都显示为 最后的 json对象。
我需要的是每一个 <a>
以在点击时显示其对应的json对象。
请看代码。
var url = "https://restcountries.eu/rest/v2/all"
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var countries = JSON.parse(xhttp.responseText)
var ul = document.getElementById('countries')
for (var i = 0; i < countries.length; i++) { //start iteration
var li = document.createElement("LI")
var img = document.createElement("IMG")
var a = document.createElement("A")
var textNode = document.createTextNode(countries[i].name)
img.setAttribute("src", countries[i].flag)
ul.appendChild(li)
li.appendChild(a)
a.appendChild(img)
a.appendChild(textNode);
a.setAttribute("title", countries[i].name)
var country = countries[i]
a.onclick = function(){ CountryClicked(country)} //pass the current JSON to the onclick function of the current <a> Node, this isn't working correctly.
}
}
}
xhttp.open('GET', url, true);
xhttp.send();
function CountryClicked(country){
var div = document.getElementById("parent-country-container")
var h1 = document.createElement("h1")
// div.appendChild(h1)
h1.appendChild(document.createTextNode(country.name + " Clicked"))
div.innerHTML = ""
div.appendChild(h1)
}
谢谢你的时间。
必须使用关闭功能才能发送正确的国家。
function CountryClicked(el) {
alert(el.name);
}
var countries = [{'flag':'xx',name:'name'}, {'flag':'xx',name:'text 2'}];
var ul = document.getElementById('countries')
for (var i = 0; i < countries.length; i++) { //start iteration
var li = document.createElement("LI")
var img = document.createElement("IMG")
var a = document.createElement("A")
var textNode = document.createTextNode(countries[i].name)
img.setAttribute("src", countries[i].flag)
ul.appendChild(li)
li.appendChild(a)
a.appendChild(img)
a.appendChild(textNode);
a.setAttribute("title", countries[i].name)
var country = countries[i];
a.onclick = (function(country){
return function(){ CountryClicked(country); }
})(country);
}
<ul id="countries"></ul>