问题
I'm following this example to make a javascript html5 DnD (drag and drop): http://www.html5rocks.com/en/tutorials/dnd/basics/
To prevent the default behavior for some browsers the default event is prevented. I understand the need. But why is there also an if statement?
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
// Why this if statement?, To me it seems double: if it is already there (if true), do it again...?
Thanks for anyone who has some time to explain this to a newbie in JavaScript.
Thanks!
回答1:
The first call isn't actually calling the function, but simply checking to see if it is defined. The code is basically asking "is the e.preventDefault()
method defined?" and then executing it if it is:
// Is preventDefault() currently defined?
if (e.preventDefault) {
// Then do it.
e.preventDefault();
}
Possible Reasoning
The likely reason that this exists is that support for event.preventDefault() wasn't added in Internet Explorer until IE9, so code similar to the following may have been more common during those dark, pre-IE9 days :
// An example of a pre-IE9 check for preventing default events
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
回答2:
Usually statements like this have to do with browser compatibility. For instance some browser might not have implemented the preventDefault()
function. That being said, I don't know of any browser that has this problem.
Older versions of Internet Explorer would not pass the event object as a parameter but instead the event was in the global scope (ie window.event
). But this code does not guard against that because if e
is undefined if(e.preventDefault)
will throw an exception.
Another candidate reason is that handleDragOver
is called from more than just the eventlistener. In the sample code this is not the case but perhaps there was a need for this at some point. I would consider this to be bad practise, and eventlistener should have only one input parameter and it should always be an event.
I'm confident you can remove the if
statement.
来源:https://stackoverflow.com/questions/36920665/why-if-statement-with-e-preventdefault-drag-and-drop-javascript