我不知道为什么"Second(带class="desc")总是空的。为什么我不能为它设置innerHTML,而我可以为第一个li标签设置innerHTML。如果我使用:
e.parentElement.children[0].innerHTML = "abc";
<==那就没问题了。如何解决这个错误?以下是我的完整代码:
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadDoc()">Get Content</button>
<div id="demo"></div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var oglasiHTML = '<div id="select">' +
'<ul>' +
'<li><a href="javascript:void(0);" onclick="return readmore('https://api.github.com/search/repositories?q=imdb+language:PHP',this);">readmore</a></li>' +
'<li class="desc"></li>' +
'</ul>' +
'</div>';
document.getElementById("demo").innerHTML = oglasiHTML;
}
};
xhttp.open("GET", "https://api.github.com/search/repositories?q=imdb+language:PHP", true);
xhttp.send();
}
function readmore(url,e) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
e.parentElement.children[1].innerHTML = "abc";
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
</body>
</html>
不工作,因为e.parentElement
返回li
节点。使用节点。nextSibling获取下一个li
节点:
if (this.readyState == 4 && this.status == 200) {
e.parentElement.nextSibling.innerHTML = "abc"; //--> <li class="desc"></li>
}
e.parentElement.parentElement.children[1].innerHTML = "abc";
e是当前元素;即a
a
的父级是li
。
现在li
只有一个子a
当前li
的父级是ul
。
现在ul
有两个孩子。
你可以给它添加值