document.getElementbyId与简写(Id.someMethod) [英] document.getElementbyId vs. shorthand (Id.someMethod)

查看:146
本文介绍了document.getElementbyId与简写(Id.someMethod)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您只能使用简写 Id.something 时,写出 document.getElementById 是否有任何好处?我很感兴趣,因为我在教程中看到一些代码,声明变量 x 等于 document.getElementById ,然后他们使用该变量,而不仅仅是使用简写:

Is there any advantage to writing out document.getElementById when you can just use the shorthand Id.something? I'm interested because I see some code online in my tutorials declaring variable x equals to document.getElementById, and then them using that variable, instead of just using the shorthand:

示例:

<code>
    var timeDisplay = document.getElementById("time");
    timeDisplay.innerHTML = message;
</code>

VS.

<code>
    time.innerHTML = message;
</code>


推荐答案

扩展我的评论,你永远不应该使用简写因为它很危险而且令人困惑。

Expanding on my comment, you should never use the "shorthand" because it is dangerous and confusing.

这是危险的,因为其他人可以在代码执行之前定义 window.time 属性,现在你的整个代码中断:

It is dangerous because someone else can defined the window.time property before your code gets executed, and now your entire code breaks:

// some one put this in the global scope
var time = new Date();

// your code
time.innerHTML = message; // nope!

https://jsfiddle.net/DerekL/6yz8j7dx/

这甚至不是主观选择。这是你几乎永远不会做 time.something

It isn't even about subjective choices. It's that you should almost never do time.something.

关于为什么令人困惑的奖金示例:

Bonus example on why it is confusing:

<div id="history"></div>

history.textContent = "Will it work?";

猜猜会发生什么?

这篇关于document.getElementbyId与简写(Id.someMethod)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆