JavaScript兼容性问题

时间:2016-11-16 21:17:08

标签: javascript compatibility

我做了很多研究,但找不到能让所有浏览器兼容脚本的代码。我希望此功能可以在Firefox,IE,Chrome等中使用,但目前,它仅适用于Chrome和旧版本,而不是Firefox版本49.任何帮助都非常感谢。代码如下:

<head>
    <script type="text/javascript">
        function toggle(tag) {
            var x = document.getElementsByName(tag)[0];
            var a = x.parentNode
            if (a.style.display == 'block') {
                a.style.display = 'none'
            } else {
                a.style.display = 'block'
            }
        }


        function init() {
            //this function will add show hide functionality to paired list items,
            //as long as the answer is a list item straight after the question list item.
            //You can also have as many separate lists as you want.
            //all lists must be contained within a div with id QA

            var obj = document.getElementById('QA');
            var elements = obj.getElementsByTagName('li');
            var index = 1
            //add javascript to question elements
            //you could also add styling to question elements here
            for (var i = 0; i < elements.length; i += 2) {
                var element = elements[i];
                element.innerHTML = "<a href='javascript:toggle(" + index + ")'>" + element.innerHTML + "</a>"
                index = index + 1
            }
            //add bookmark to answer elements and add styling
            var index = 1
            for (var i = 1; i < elements.length; i += 2) {
                var element = elements[i];
                element.innerHTML = "<a name='" + index + "' id='" + index + "'></a>" + element.innerHTML
                index = index + 1
                element.style.padding = '0px 0px 10px 20px' //add indent to answer
                element.style.listStyleType = 'none' //remove bullet
                element.style.display = 'none' //hide answer element
            }
        }

        window.onload = init;
    </script>
</head>

1 个答案:

答案 0 :(得分:0)

根据您身体的结构,Document.getElementsByName()在不同的浏览器之间可能会有不同的表现:

  

getElementsByName方法在不同浏览器中的工作方式不同。在IE&amp; Opera,getElementsByName()方法还将返回具有指定值的id属性的元素。所以你应该注意不要使用与名称和ID相同的字符串。

Source