简体   繁体   English

document.getElementById的值是什么?

[英]what is the value of document.getElementById?

I am an experienced programmer but I am trying to learn javascript and I learn best by seeing how things work. 我是一位经验丰富的程序员,但是我尝试学习javascript,并且通过观察事物的工作原理来学习最好。 I found a script that fades images in an array. 我发现了一个脚本,可以淡化数组中的图像。 This is the script 这是脚本

window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var d=document, imgs = new Array(), zInterval = null, current=0, pause=false;

function so_init() {
if(!d.getElementById || !d.createElement)return;

css = d.createElement("link");
css.setAttribute("href","xfade2.css");
css.setAttribute("rel","stylesheet");
css.setAttribute("type","text/css");
d.getElementsByTagName("head")[0].appendChild(css);

imgs = d.getElementById("imageContainer").getElementsByTagName("img");
for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;

setTimeout(so_xfade,1000);
}

function so_xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current+1]?current+1:0;

nOpacity = imgs[nIndex].xOpacity;

cOpacity-=.05; 
nOpacity+=.05;

imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;

setOpacity(imgs[current]); 
setOpacity(imgs[nIndex]);

if(cOpacity<=0) {
    imgs[current].style.display = "none";
    current = nIndex;
    setTimeout(so_xfade,1000);
} else {
    setTimeout(so_xfade,50);
}

function setOpacity(obj) {
    if(obj.xOpacity>.99) {
        obj.xOpacity = .99;
        return;
    }
    obj.style.opacity = obj.xOpacity;
    obj.style.MozOpacity = obj.xOpacity;
    obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
}

}

The part I am having difficulty with are these lines 我遇到的困难是这些线

window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

and

if(!d.getElementById || !d.createElement)return;

Everything I can find shows both window.addEventListener and d.getElementById are methods of the window and document objects respectively. 我可以找到的所有内容都显示window.addEventListener和d.getElementById分别是window对象和document对象的方法。 So what is their values when they are called with out any parameters, and in these cases what conditions would make them true and what condition would make them false. 因此,在不带任何参数的情况下调用它们时,它们的值是什么?在这些情况下,什么条件会使它们为真,什么条件会使它们为假。

The code is checking to see if those methods exist and if they don't is using alternate methods (browser compatibility issues) or aborting a function that will just fail anyway. 代码正在检查这些方法是否存在,以及是否不使用其他方法(浏览器兼容性问题)或中止一个无论如何都会失败的函数。

This line: 这行:

window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

is checking to see if window.addEventListener exists. 正在检查是否存在window.addEventListener If it does, it's calling it. 如果是这样,它正在调用它。 If it doesn't exist, it's calling window.attachEvent . 如果不存在,则调用window.attachEvent This is to deal with older versions of IE that didn't have addEventListener , but had a similar function called attachEvent . 这是为了处理IE的旧版本,该版本不具有addEventListener ,但具有类似的函数叫做attachEvent Most sane programmers would put this abstraction in a utility function or a shim that you call to abstract this out of normal programming. 大多数理智的程序员会将这种抽象放入实用程序函数或您调用的垫片中,以将其从常规编程中抽象出来。 This logic is still needed in all versions of IE before IE9. IE9之前的所有版本的IE仍需要此逻辑。

This line: 这行:

if(!d.getElementById || !d.createElement)return;

is aborting the function (with an early return) if either of getElementById or createElement don't exist as properties/methods on object d . 如果getElementByIdcreateElement任何一个都不作为对象d属性/方法存在,则将中止该函数(并提前返回)。 This check is no longer needed as these methods exist in all currently used browsers (added to IE in 5.5, present in Firefox, Chrome and Safari in 1.0). 不再需要进行此检查,因为所有当前使用的浏览器中都存在这些方法(5.5中已添加到IE,1.0中包含在Firefox,Chrome和Safari中)。

if(!d.getElementById || !d.createElement)return;

This line tests to see if the methods exist at all, ie, it tests if the browser supports both methods. 此行进行测试以查看这些方法是否存在,即,它测试浏览器是否支持这两种方法。 Dealing with browser compatibility isn't fun, but it's better to test for functionality rather than browser version. 处理浏览器兼容性并不好玩,但是最好测试功能而不是浏览器版本。

If you use a function name without parentheses it doesn't call the function, it gives you a reference to the function. 如果使用不带括号的函数名称,则不会调用该函数,它为您提供了对该函数的引用。 A really simple example: 一个非常简单的示例:

function f1() { alert("hi"); }

var f2 = f1;    // This doesn't call the f1 function, it takes a reference
                // to it and assigns it to f2.
f2();           // Can call f2 since it refers to the same function; alerts "hi"

You can see from that the function names are really just variables that happen to hold references to functions rather than to strings or numbers or whatever, something that is perhaps even more obvious if you define a function like this: 从中可以看到,函数名称实际上只是变量,碰巧会保留对函数的引用,而不是对字符串或数字等的引用,如果您定义如下函数,则可能会更明显:

var f3 = function() { alert("hello") };
f3();           // "hello"

So, with that background what does it mean to say if (someFunctionName) ? 那么,在这种背景下说if (someFunctionName)是什么意思? In JS, an expression is considered "truthy" not only if it is a boolean true but if it evaluates to be a non-empty string, a non-zero number, or any object (even an empty object). 在JS中,表达式不仅是布尔值true,而且计算结果是非空字符串,非零数字或任何对象(甚至是空对象),都被认为是“真实的”。 Empty strings, zero, null, undefined and NaN are all "falsy". 空字符串,零,空,未定义和NaN都是“虚假的”。 This distinction between boolean true and "truthy" is very important in JavaScript. 在JavaScript中,布尔true与“ true ”之间的区别非常重要。 JS functions are a type of object. JS函数是一种对象。 So: 所以:

if (someFunctionName)
// is testing if someFunctionName is "truthy" and is a shortcut way of saying
if (someFunctionName != undefined)
// also equivalent to
if (typeof someFunctionName != "undefined")

The second example you ask about, if(d.getElementById) , is a test that the object d (which is set to document ) has a method called getElementById . 您要询问的第二个示例if(d.getElementById)是测试对象d (设置为document )是否具有名为getElementById的方法的测试。 In a general sense this is because a long time ago not all browsers supported that method so this code was intended to allow the code to run in all browsers without errors. 一般而言,这是因为很久以前并不是所有的浏览器都支持该方法,因此该代码旨在使代码在所有浏览器中都能正常运行。 In practice document.getElementById() has been supported since at least the days of IE5 so this test is redundant. 实际上,至少从IE5以来,就一直支持document.getElementById() ,因此该测试是多余的。

The first example you asked about is still relevant though because IE8 and older does not support window.addEventListener . 您询问的第一个示例仍然有用,因为IE8和更早版本不支持window.addEventListener So the code: 所以代码:

window.addEventListener ? window.addEventListener("load",so_init,false)
                        : window.attachEvent("onload",so_init);

is using the ternary operator ? : 正在使用三元运算符? : ? : to test whether window.addEventListener is defined. ? :测试是否定义了window.addEventListener If it is, it calls it, otherwise it calls window.attachEvent (which is the old IE equivalent). 如果是,它将调用它,否则它将调用window.attachEvent (与旧版IE等效)。 All modern browsers support one or the other. 所有现代浏览器都支持一种。

In both cases, the script seems to be practicing progressive enhancement techniques and graceful degradation techniques. 在这两种情况下,脚本似乎都在实践渐进式增强技术和优美的降级技术。 Check out the article, but in short, it's checking whether the browser supports these functions. 请查看本文,但总而言之,它正在检查浏览器是否支持这些功能。

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

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