我可以减少这段 JavaScript 代码吗?
我可以减少
function n()
{
var a;
if(a = document.getElementById('fb0'))
{
a.onclick = i0;
document.getElementById('fb1').onclick = i1;
}
}
到
function n()
{
if(document.getElementById('fb0').onclick = i0)
{
document.getElementById('fb1').onclick = i1;
}
}
我现在没有调试器吗?我知道 document.getElementById('fb0')
返回一个值,因为第一个代码段工作正常。但是否需要在 if 语句中计算赋值呢?
Can I reduce
function n()
{
var a;
if(a = document.getElementById('fb0'))
{
a.onclick = i0;
document.getElementById('fb1').onclick = i1;
}
}
to
function n()
{
if(document.getElementById('fb0').onclick = i0)
{
document.getElementById('fb1').onclick = i1;
}
}
I don't have a debugger right now. I know that document.getElementById('fb0')
returns a value because the first snippet works fine. But does it need the assignment to be evaluated in the if statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不能。
document.getElementById('fb0')
,正如函数名称所示,返回 id 等于fb0
的html 元素
。之后您将访问属性onclick
。但如果 get 失败,则会破坏脚本。在第一个场景中,您测试分配是否有效,如果有效,则意味着该元素存在并且仅在存在时才执行。
这些是不同的行为。
No, you can't.
document.getElementById('fb0')
, as the function name already says, returns thehtml element
with has the id equal tofb0
. After that you are accessing the attributeonclick
. But it the get fails it will break the script.On the first scenario you test if the assignment works, if does it means the element exists and will only execute if it exists.
Those are different behaviors.
并不真地;如果
getElementById('fb0')
不返回任何内容,您的页面将收到错误,而在第一种情况下则不会。Not really; if
getElementById('fb0')
doesn't return anything your page will get an error, and in the first case it wouldn't.要检查“document.getElementById('fb0')”是否返回元素或 null,第二个版本不会执行此操作,如果没有 id 为“fb0”的元素,则会抛出错误。如果您在某个时刻不从 DOM 中删除“fb0”元素,则第二个版本是可以的。
To check if "document.getElementById('fb0')" returns an element or null, the second version don't do it and an error will be throw if there is no element with id "fb0". The second version is ok if you don't remove the "fb0" element from the DOM at some point.
如果
document.getElementById('fb0')
不存在,则会失败。document.getElementById('fb0').onclick
在这种情况下没有多大意义。That would fail if
document.getElementById('fb0')
were not to exist.document.getElementById('fb0').onclick
wouldn't mean much in that case.如果您通过 ID 进行大量 DOM 选择,请制作该方法的简化版本:
在这种情况下,在条件内进行赋值不会节省任何字符。与声明的长度相同。
If you do a lot of DOM selection by ID, make a shortened version of that method:
In this case, doing the assignment inside the condition doesn't save you any characters. It's the same length to do it with the declaration.