Javascript无法看到动态生成的元素
Javascript cannot see dynamically generated elements?
我不知道为什么新生成的元素不能被下一个调用的函数看到?谢谢你的帮助!!解决方案:添加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();
在加载元素之前尝试在DOM中定位元素是不起作用的(一旦遇到它,脚本就会立即运行。如果它在文件中的html之上,则元素还不存在,因此找不到)
类似地,启动AJAX请求,然后将其视为同步操作(在执行更多代码之前等待操作完成)将不起作用。
在第一个例子中,在浏览器有时间解析HTML之前就遇到了代码,因此当你试图获得对它的引用时,DOM中不存在该元素——这可以通过等待文档发出加载完成的信号来解决。
第二个问题是,在激发birth
函数之后,立即激发whereIsTheChildren
函数。不幸的是,ajax请求仍处于挂起状态,因此我们还没有得到需要使用的结果。这是通过将对whereIsTheChildren
的调用放在ajax请求的成功回调中来解决的。
我举了一个快速的例子,使用vanillaJS和PHP——只需将对PHP文件的请求替换为对CGI的请求。
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>
修改为在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');
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;
}
<div id="Marry" class="mom">Marry</div>
<div id="Liz" class="mom">Liz</div>
<div id="Betty" class="mom">Betty</div>
你把它放在window.onload事件处理程序中了吗?你的代码正在工作,检查这个小提琴
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();
}
相关文章:
- 将列表元素动态添加到ul元素中
- 将输入 html 元素动态关联到颜色选取器
- 媒体元素 - 动态加载音频
- 根据其内部元素动态更改 CSS
- 编写脚本以向元素动态添加.current(类似活动类)的场景
- 使用knockoutjs虚拟元素动态创建html部分
- 将JS中的元素动态添加到XUL中
- 如何从jquery中获得元素动态附加的完整表
- 使用jquery向li元素动态添加类
- 点击事件不't在尝试将元素动态添加到<ul>标签
- 使用Knockout.js Issue将元素动态添加到嵌套列表中
- 如何从DOM元素动态禁用popover
- 将样式元素动态插入DOM的最后一种跨浏览器方式
- 无法将元素动态添加到数组中
- 指令如何等待元素'动态插值属性被处理?
- 设置活动元素和非活动元素(动态)
- 是否可以使用JS/PHP为网页中的元素动态分配ID
- 如何制造<光>元素动态调整以填充浏览器窗口的整个宽度
- 基于页面元素动态构建菜单结构
- 向现有元素动态添加删除绑定