简体   繁体   English

跨浏览器使用getElementsByTagName获取脚本标记不一致

[英]Getting the script tag using getElementsByTagName inconsistent across browsers

I have the following code: 我有以下代码:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var script_obj = document.getElementsByTagName('script')
        alert(typeof script_obj);
    });
</script>

When I run this in Firefox (v21) and Chrome (v29) I get object as the result, but in Safari (v5) I get function . 当我在Firefox(v21)和Chrome(v29)中运行此程序时,得到的是object ,但是在Safari(v5)中,我得到了function

Why is this?! 为什么是这样?!

In the rest of my script I'm iterating through script_obj to get the .src data, but my count function that determines the length of the haystack (ie script_obj ) has a check that returns false if the haystack is not an array or an object , so it is failing in Safari. 在脚本的其余部分中,我遍历script_obj以获取.src数据,但是确定haystack长度的count函数(即script_obj )具有一个检查,如果该haystack不是arrayobject则该检查返回false ,因此在Safari中失败。 Is there another way I can do this instead of using document.getElementsByTagName('script') ?! 还有另一种方法可以代替使用document.getElementsByTagName('script')吗?

document.getElementsByTagName() returns a NodeList . document.getElementsByTagName()返回一个NodeList Although a NodeList is not an Array, it does have a length property just like an Array. 尽管NodeList不是Array,但它确实具有length属性,就像Array一样。 So you don't need to do anything special to count the number of items in it. 因此,您无需执行任何特殊操作即可计算其中的项目数。 Not sure what your count function is doing, but you can just do this: 不知道计数功能在做什么,但是您可以执行以下操作:

> var script_obj = document.getElementsByTagName('script');
> alert(script_obj.length); // will alert '22' or whatever

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM