简体   繁体   English

使用Javascript的getElementById

[英]Usage of Javascript's getElementById

In sample code of the yui library, I see this notation: 在yui库的示例代码中,我看到了这种表示法:

var obj = document.getElementById("coffee_msg");
obj.style.display = 'block';

As obj is only used once, I would rather prefer this: 由于obj只使用过一次,我宁愿这样做:

document.getElementById("coffee_msg").style.display = 'block';

Is there any reason why the first notation is used in the yui library and many other places? 有没有理由在yui库和其他许多地方使用第一种符号? Are there incompatibilities with certain browsers? 是否与某些浏览器不兼容?

There isn't a "real" reason, just to make the code a little bit more readable. 没有“真正的”原因,只是为了使代码更具可读性。

Just like with: 就像:

var myAge = 26;
var myAgeNextYear = myAge + 1;

VS: VS:

var myAgeNextYear = 26 + 1;

My personal preference is to keep a reference to the obj only if I'm using it more than once. 个人的偏好是只有在我不止一次使用它时才会保留对obj的引用。

If you only need to set one property it doesn't matter at all (as long as you do not want to check if the return value is valid before trying to access a property of it). 如果你只需要设置一个属性就完全无关紧要(只要你不想在尝试访问它的属性之前检查返回值是否有效)。

However, if you have multiple properties you'll want to do the lookup only once (even though an id lookup is extremely fast), so assigning the element to a variable is the way to go in that case. 但是,如果你有多个属性,你只想进行一次查找(即使id查找非常快),所以在这种情况下将元素分配给变量就是这样。

Of course you could make this even shorter with jQuery: $('#coffee_msg').show() 当然你可以用jQuery来缩短它: $('#coffee_msg').show()
Also has the advantage that you do not get an error if the element does not exist for some reason. 还有一个好处是,如果元素由于某种原因不存在,则不会出现错误。 And if you want to set multiple CSS properties etc, you can simply use a function that does that for you with a single call or chain multiple calls to different jQuery methods. 如果你想设置多个CSS属性等,你可以简单地使用一个函数来为你做一次调用或链多次调用不同的jQuery方法。

The two different ways work exactly the same. 两种不同的方式完全相同。 Using a temporary obj variable could be useful to improve readability of the code (but it should be given a name better than obj in that case). 使用临时obj变量可能有助于提高代码的可读性(但在这种情况下应该给出比obj更好的名称)。

The first option is useful because it improves readability, it also makes the obj variable available immediately for other use. 第一个选项很有用,因为它提高了可读性,它还使obj变量可立即用于其他用途。 I would use this example personally. 我会亲自使用这个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM