我不知道为什么新生成的元素不能被下一个被调用的函数看到?感谢帮助!! 解决方案:添加async:false以禁用异步功能,以确保在出生过程后执行test-output-2和test-output-3。默认情况下,ajax使用async:true,就像多线程一样。
function birth(mom)
{
$.ajax(
{url: "/cgi-bin/count.cgi", // return 3 for sure
async: false, // add this to disable asynchronous feature to make sure test-output-2 and test-output-3 executed after birth process
success: function(xkids) // xkids is 3
{
for( var i = 0; i < xkids; i++ )
{
mom.appendChild(document.createElement("div"));
mom.children[i].setAttribute("id", "child-"+i);
}
document.getElementById("test-output-1").innerHTML = mom.children.length; // now there are 3 children
}
});
document.getElementById("test-output-2").innerHTML = mom.children.length; // there are 0 children if async: true
}
var marry = document.getElementById("Marry"); // currently no child
birth(marry);
function whereIsTheChildren()
{
document.getElementById("test-output-3").innerHTML = marry.children.length; // there are 0 children if async: true
}
whereIsTheChildren();
答案 0 :(得分:1)
在加载之前尝试在DOM中找到一个元素是行不通的(脚本会在遇到它时立即运行。如果这个文件位于文件中的html之上,那么该元素将不会存在,因此不会被找到)
类似地,触发一个AJAX请求,然后表现为同步操作(等待操作在执行更多代码之前完成)将不起作用。
在第一个实例中,在浏览器有时间解析HTML之前遇到代码,因此当您尝试获取对它的引用时,DOM中不存在该元素 - 这可以通过等待来修复该文件表明它已完成装载。
第二个问题是在触发birth
函数后立即触发whereIsTheChildren
函数。不幸的是,ajax请求仍然悬而未决,所以我们还没有从中得到我们需要使用的结果。通过将调用whereIsTheChildren
置于ajax请求的成功回调中来解决此问题。
我使用vanilla JS和PHP编写了一个快速示例 - 只需将请求替换为带有CGI的php文件。
<强> getKidCount.php 强>
<?php
echo "3";
?>
<强>的index.html 强>
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
//birth(3, byId("Marry") );
myBirth( byId('Marry') );
}
function myBirth(parentElem)
{
myAjaxGet('getKidCount.php', onAjaxSuccess, onAjaxFail);
function onAjaxSuccess(ajax)
{
var numKids = parseInt(ajax.responseText);
for (var i=0; i<numKids; i++)
{
var div = document.createElement('div');
div.id = ("child-"+i);
parentElem.appendChild(div);
}
document.getElementById("test-output-1").innerHTML = parentElem.children.length; // now there are 3 children
whereIsTheChildren();
}
function onAjaxFail(ajax)
{
alert("Ajax failed. :(");
}
}
function whereIsTheChildren()
{
document.getElementById("test-output-2").innerHTML = byId('Marry').children.length; // there are 0 children
}
/*
function birth(xkids, mom)
{
for( var i = 0; i < xkids; i++ )
{
mom.appendChild(document.createElement("div"));
mom.children[i].setAttribute("id", "child-"+i);
}
document.getElementById("test-output-1").innerHTML = mom.children.length; // now there are 3 children
}
function birth(mom)
{
$.ajax(
{url: "/cgi-bin/count.cgi", // return 3 for sure
success: function(xkids) // xkids is 3
{
for( var i = 0; i < xkids; i++ )
{
mom.appendChild(document.createElement("div"));
mom.children[i].setAttribute("id", "child-"+i);
}
document.getElementById("test-output-1").innerHTML = mom.children.length; // now there are 3 children
}
document.getElementById("test-output-2").innerHTML = mom.children.length; // now there are 0 children
}
*/
</script>
</head>
<body>
<div id='test-output-1'></div>
<div id='test-output-2'></div>
<div id='Marry'></div>
</body>
</html>
答案 1 :(得分:1)
修改为在DOM中表示也在console.log中
function birth(xkids, mom) {
var mom = document.querySelector(mom);
console.log('Mom: '+mom.id);
for (var i = 0; i < xkids; i++) {
mom.appendChild(document.createElement("div"));
mom.children[i].setAttribute("id", "child-" + i);
mom.children[i].innerHTML = mom.children[i].id;
}
console.log(mom.id+' has '+mom.children.length+' children');
var test = document.createElement("output");
document.body.appendChild(test);
test.value = mom.id + ' ' + mom.children.length;
}
birth(3, '#Marry');
birth(5, '#Liz');
birth(2, '#Betty');
&#13;
div {
outline: 1px solid black;
width: 100px;
height: 30px;
}
output {
outline: 1px solid red;
color: red;
margin: 10px auto;
padding: 2px;
float: left;
}
.mom {
outline: 1px dashed blue;
width: 100px;
height: auto;
padding: 5px;
display: inline-block;
}
&#13;
<div id="Marry" class="mom">Marry</div>
<div id="Liz" class="mom">Liz</div>
<div id="Betty" class="mom">Betty</div>
&#13;
答案 2 :(得分:0)
你把它放在window.onload事件处理程序中吗?您的代码正常运行,请查看此fiddle
window.onload=function(){
function birth(xkids, mom)
{
for( var i = 0; i < xkids; i++ )
{
mom.appendChild(document.createElement("div"));
mom.children[i].setAttribute("id", "child-"+i);
}
document.getElementById("test-output-1").innerHTML = mom.children.length; // now there are 3 children
}
var marry = document.getElementById("Marry"); // currently no child
birth(3, marry);
function whereIsTheChildren()
{
document.getElementById("test-output-2").innerHTML = marry.children.length; // there are 0 children
}
whereIsTheChildren();
}