[英]How do I access a dynamically loaded element in jquery or javascript?
Okay here is the scenerio that is bugging me. 好的,这里是烦扰我的场景。 I need to get the list of all elements within a dom, even the once that are dynamically loaded.
我需要获取dom中所有元素的列表,甚至是动态加载的元素。
So say for instance a script element is created with 所以说例如创建一个脚本元素
var script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';
$("head").append(script);
and if I do following that: 如果我这样做:
var doc = document.documentElement;
var scripts = doc.getElementsByTagName("script");
for (var idx in scripts)
{
var s = scripts[idx];
if (!s.src) continue;
s = s.src;
alert(s);
}
How come I don't see the dynamically added script? 为什么我看不到动态添加的脚本? I tried it in Jquery with the same results.
我在Jquery中尝试了相同的结果。
Does anyone know how this can be achieved? 有谁知道如何实现这一目标? perhaps with dom refreshing?
也许与dom清爽?
*Just to be clear: All I want is to loop through the dom and find the 'src' attributes of the 'script' elements, even the one that are dynamically loaded. *只是要明确:我想要的只是遍历dom并找到'script'元素的'src'属性,甚至是动态加载的元素。
Did you add it to the dom...? 你把它添加到dom ......?
var script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';
$(script).appendTo("head"); //or body
You need to append the dynamically created script to the DOM somehow first. 您需要首先以某种方式将动态创建的脚本附加到DOM。 Here's a foolproof way:
这是一个万无一失的方式:
var ref=document.getElementsByTagName('script')[0],
script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';
ref.parentNode.insertBefore(script, ref);
It looks like NeXXeuS is correct. 看起来NeXXeuS是正确的。 You can also append the your new element without jQuery:
你也可以在没有jQuery的情况下附加你的新元素:
var newNode = document.createElement("script");
newNode.type = "text/javascript";
newNode.src = "somescript.js";
document.body.appendChild(newNode);
Try running it inside the JavaScript console in Firefox or Chrome and you will see the new script get added appended to the body tag in this case. 尝试在Firefox或Chrome中的JavaScript控制台中运行它,在这种情况下,您将看到新脚本被添加到body标签中。
You are appending it with jquery, why not look for it with jQuery? 你用jquery附加它,为什么不用jQuery寻找呢?
var scripts = $('script') var scripts = $('script')
or even 甚至
var scripts = $('script[src]') var scripts = $('script [src]')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.