getElementsByTagName()不起作用

时间:2013-02-20 03:37:22

标签: javascript html getelementbyid

<!DOCTYPE html>
<html>
<head> <script language="javascript" type="text/javascript">  <pre> function whatImg(){
            var str = getUrlVars()["obj"];
            document.getElementByTagName('img').src = 'images/dog.png';
            }                                   
        function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {vars[key] = value;});
            return vars;
        }<code>                             
    </script>

</head>

<body>

    <div data-role="page">
        <img src="images/keys.png" id="image"/>
        <script type="text/javascript"  language="javascript">  whatImg();</script>     
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

getElementsByTagName而非getElementByTagName

并使用document.getElementByTagName('img')[0].src代替

你最好在html代码下面编写js代码:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div data-role="page">
            <img src="images/keys.png" id="image" />
        </div>
        <script>
            function whatImg() {
                var str = getUrlVars()["obj"];
                document.getElementsByTagName('img')[0].src = 'images/dog.png';
            }

            function getUrlVars() {
                var vars = {};
                var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
                    vars[key] = value;
                });
                return vars;
            }
            whatImg();
        </script>
    </body>
</html>

答案 1 :(得分:1)

因为没有getElementByTagName这样的东西。您忘记了s.getElementsByTagName

它还返回NodeList,这意味着你必须这样做:

var ele = document.getElementsByTagName('img');
ele[0].src = 'images/dog.png';

有时使用id获取元素可能更好:

var ele = document.getElementById('image');
ele.src = 'images/dog.png';

答案 2 :(得分:0)

返回HTMLCollection,因此您必须对其进行循环并为每个src属性分配该值。