I'm wondering how to merge these JS if/else statements correctly?
if (window.addEventListener) { window.addEventListener('dosomething', foo, false); }
else { document.addEventListener('dosomething', foo, false); }
if (window.attachEvent) { window.attachEvent('dosomething', foo); }
else { document.attachEvent('dosomething', foo); }
EDIT I
The original code was:
if (window.attachEvent) { window.attachEvent('dosomething', foo); }
else if (window.addEventListener) { window.addEventListener('dosomething', foo, false); }
else { document.addEventListener('dosomething', foo, false); }
Now, I'd like to add
document.attachEvent('dosomething'开发者_JAVA百科, foo);
here.
EDIT II
Turns out, "document.addEventListener" / "document.attachEvent" are redundant, so I'll leave it to
if (window.addEventListener) { window.addEventListener('dosomething', foo, false); }
else if (window.attachEvent) { window.attachEvent('dosomething', foo); }
Thanks everyone!
The original code looks OK except that it's better to check window.addEventListener first since that is the standard DOM Events interface. attachEvent should only be used as a fallback for IE versions before 9.
I don't know what you're doing with checking for the methods on both window and document. If the method exists on one it will by necessity exist on the other, so your extra option will never occur.
If there is neither window.addEventListener nor window.attachEvent, you are using an ancient browser or a limited (eg. mobile phone) browser. Neither of those will have the same method on document; if they support events at all you would only be able to bind using old-school window.onsomething= function() {...}; style events.
Both conditions perform a different task, you should not join them. However, you may want to have a look at javascript ternary operator to lessen your code.
You don't want to "merge" these if statements. You are checking for two totally different things, even though they are related. I strongly urge you not to.
Leave them as they are.
If you really want to improve your code use a js library that can handle unified events for all browsers (i.e. jQuery).
You can use the || operator to shorten it to this:
(window.addEventListener || document.addEventListener)('dosomething', foo, false);
(window.attachEvent || document.attachEvent)('dosomething', foo);
This works because the expression expr1 || expr2 is evaluated as follows:
Returns
expr1if it can be converted to true; otherwise, returnsexpr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
Wasn't the advice to formulate if/else statements in JS like
if (foo) {
bar();
} else {
bla();
}
to avoid semicolon insertion issues?
加载中,请稍侯......
精彩评论