【发布时间】:2018-12-02 19:25:41
【问题描述】:
我正在使用以下功能,我喜欢它:var $ = function( id ) { return document.getElementById( id ); };
对于我当前的代码,我仅会引用每个元素的 value。
所以我想,“为什么不更新我的函数以包含.value?
所以这很好用:
var $ = function( id ) { return document.getElementById( id ); };
$("foo").value = whatever // WORKS JUST FINE :)
但这会中断:
var $ = function( id ) { return document.getElementById( id ).value; };
$("foo") = whatever // Left side of assignment is not a reference
我想我知道发生了什么,但由于很难用语言表达,我宁愿假设我错了。
那么这里发生了什么?
顺便说一句,请随时发表评论:
【问题讨论】:
-
$("foo").value = whatever将whatever分配给返回的节点对象的value属性。$("foo") = whatever尝试将值分配给一个值(类似于将一个字符串分配给另一个字符串),你说得对,这是一个 ReferenceError。 -
document.getElementById('foo').value实际上 is (一个计算结果的表达式)一个引用。你的问题是函数调用$("foo")不是,因为函数不能返回引用。
标签: javascript error-handling reference referenceerror