在下面的例子中,为什么输入"test"的"值"不会更新为"second"?
<html>
<head>
<script type="text/javascript">
getText = function() {
var test = document.getElementById('test').value;
test = "second";
//note: if you insert "alert(test)" it returns "second"
}
</script>
</head>
<body>
<label for="test">Test </label><input type="text" id="test" value="first" onclick="getText()"></input>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
因为Javascript将x指定为值而不是对原始对象的引用.
例如,您可以改为:
function setText(x) {
document.getElementById('test').value = x;
}
getText = function() {
return document.getElementById('test').value;
}
Run Code Online (Sandbox Code Playgroud)
您设置的值setText()将反映出来getText(),因为它getText()也将使用引用对象的值,而不是值的副本.
编辑
正如布莱恩指出的那样,这将是一个全球范围的参考副本:
var test = document.getElementById('test');
function setText(x) {
test.value = x;
}
getText = function() {
return test.value;
}
Run Code Online (Sandbox Code Playgroud)
原始test变量存储对元素的引用,而不是与元素的属性关联的值.
| 归档时间: |
|
| 查看次数: |
32901 次 |
| 最近记录: |