为什么一个需要getElementById而另一个不需要

时间:2013-11-07 02:07:00

标签: javascript html

为什么这样做

app.prints(address,list.options[list.selectedIndex].value);

但这不是吗?

app.prints(status,macAddress);

的JavaScript

var hey = 5;
var app = {
    createList: function () {
        for (var i = 0; i < 5; i++) {
            list.options[i] = new Option(hey + i, "mac" + i);
        }
        app.prints(address, list.options[list.selectedIndex].value);
    },
    prints: function (location, message) {
        location.innerHTML = message;
    },
    manageConnection: function () {
        var macAddress = list.options[list.selectedIndex].value;
        app.prints(status, macAddress);
    }
}

HTML

<!DOCTYPE html>
<!-- Don't panic! All this 
    code looks intimidating but eventually it  will make sense. -->
<html lang="en">

<head>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script type="text/javascript" src="ECMA.js"></script>
    <title>My LCD code</title>
</head>

<body onload="app.initialize();">
    <p>Welcome to the LCD software</p>
    <select id="list" onchange="app.prints
    (address,list.options[list.selectedIndex].value);"></select>
    <div id="address"></div>
    <button id="connect" onclick="app.manageConnection();">Connect</button>
    <div id="status">hi</div>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

区别在于全局status变量has already been defined by the browser代表状态栏中的文字。并且,浏览器不允许引用该元素来替换它。

为避免命名冲突,您可以重命名该元素。

但是,你真的不应该依赖于id的自动全局变量。并非所有浏览器都实现该功能,有些仅在某些模式下实现。

var list = document.getElementById('list');
var address = document.getElementById('address');
app.prints(address, list.options[list.selectedIndex].value);