【问题标题】:Why is document.getElementById('foo').value not a reference?为什么 document.getElementById('foo').value 不是参考?
【发布时间】: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 = whateverwhatever 分配给返回的节点对象的value 属性。 $("foo") = whatever 尝试将值分配给一个值(类似于将一个字符串分配给另一个字符串),你说得对,这是一个 ReferenceError。
  • document.getElementById('foo').value 实际上 is (一个计算结果的表达式)一个引用。你的问题是函数调用$("foo") 不是,因为函数不能返回引用。

标签: javascript error-handling reference referenceerror


【解决方案1】:

一个元素的.value实际上是一个setter/getter。当以下

document.getElementById( id ).value

被评估为一个 表达式(就像在$ 中,你试图返回它),而不是被分配,getter 被调用,它评估为一个原语。所以,对口译员:

return document.getElementById( id ).value;

变成类似的东西

return 'someValue';

所以,当调用$ 时,会返回一些字符串,但就像

'someValue' = 'newValue'

没有用,也没有

$("foo") = 'newValue';

对于你想要做的工作,你必须调用 setter,通过分配给.valueproperty。一旦 .value 被评估为表达式(例如在 return 的右侧),您就已经调用了 getter。

调用setter的一种可能方法是:

const set$ = (id, newVal) => {
  document.getElementById(id).value = newVal;
};
set$('foo', 'myNewVal');

【讨论】:

  • 感谢您的解释!所以本质上,虽然我们不能引用.value,但我们可以查找getElementByID() 各自的.setValue() 并使用它就好了吗?
  • 你要么必须分配给.value.value 在左侧,要么调用/做一些事情。
【解决方案2】:

在第二个函数中,$("foo") 的返回值是一个字符串。您不能分配给字符串:

var $ = function( id ) { return document.getElementById( id ).value; };
console.log(typeof $("foo"), $("foo"))
<input id="foo" value = "Bar"/>

有很多选择。您可以让您的函数采用第二个参数来设置值:

var $ = function(id, val) {
  let el = document.getElementById(id)
  if (val !== undefined) {
    el.value = val
  }
  return el
}

console.log($("foo", "test"))
<input id="foo" value="Bar" />

但如果只是返回元素,然后分配值或创建一个新的设置值函数,可能会更清楚。

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多