0

为什么这行得通

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>
4

1 回答 1

2

不同之处在于浏览器已经定义了一个全局status变量来表示状态栏中的文本。而且,浏览器不允许引用元素来替换它。

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

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

var list = document.getElementById('list');
var address = document.getElementById('address');
app.prints(address, list.options[list.selectedIndex].value);
于 2013-11-07T02:12:05.857 回答