evento.La función preventDefault() no funciona en IE


Lo siguiente es mi código JavaScript (mootools):

$('orderNowForm').addEvent('submit', function (event) {
    event.preventDefault();
    allFilled = false;
    $$(".required").each(function (inp) {
        if (inp.getValue() != '') {
            allFilled = true;
        }
    });

    if (!allFilled) {
        $$(".errormsg").setStyle('display', '');
        return;
    } else {
        $$('.defaultText').each(function (input) {
            if (input.getValue() == input.getAttribute('title')) {
                input.setAttribute('value', '');
            }
        });
    }

    this.send({
        onSuccess: function () {
            $('page_1_table').setStyle('display', 'none');
            $('page_2_table').setStyle('display', 'none');
            $('page_3_table').setStyle('display', '');
        }
    });
});

En todos los navegadores excepto IE, esto funciona bien. Pero en IE, esto causa un error. Tengo IE8, así que mientras usaba su depurador JavaScript, descubrí que el objeto event no tiene un método preventDefault que está causando el error y, por lo tanto, el formulario se envía. El método es compatible en el caso de Firefox (que descubrí usando Firebug).

Alguna Ayuda?

Author: danwellman, 2009-06-16

11 answers

En IE, puede usar

event.returnValue = false;

Para lograr el mismo resultado.

Y para no obtener un error, puede probar la existencia de preventDefault:

if(event.preventDefault) event.preventDefault();

Puedes combinar los dos con:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);
 454
Author: Alsciende,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-12 13:17:20

Si enlaza el evento a través de la función addEvent de mootools, su controlador de eventos obtendrá un evento fijo (aumentado) pasado como parámetro. Siempre contendrá el método preventDefault ().

Pruebe este violín para ver la diferencia en el enlace de eventos. http://jsfiddle.net/pFqrY/8 /

// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
 alert(typeof(event.preventDefault));
});

// preventDefault missing in IE
<button
  id="htmlbutton"
  onclick="alert(typeof(event.preventDefault));">
  button</button>

Para todos los usuarios de jQuery puede corregir un evento cuando sea necesario. Digamos que usaste HTML onclick=".."y obtener un evento específico de IE que carece de preventDefault (), solo usa este código para conseguirlo.

e = $.event.fix(e);

Después de eso, e.preventDefault(); funciona bien.

 23
Author: oldwizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-05 07:52:44

Sé que este es un post bastante antiguo, pero acabo de pasar algún tiempo tratando de hacer que este trabajo en IE8.

Parece que hay algunas diferencias en las versiones de IE8 porque las soluciones publicadas aquí y en otros hilos no funcionaron para mí.

Digamos que tenemos este código:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

En mi IE8 preventDefault() el método existe debido a jQuery, pero no funciona (probablemente debido al punto de abajo), por lo que esto fallará.

Incluso si establezco la propiedad returnValue directamente a false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

Esto tampoco funcionará, porque acabo de establecer alguna propiedad de jQuery custom event object.

La única solución que funciona para mí es establecer la propiedad returnValue de la variable global event así:

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Solo para que sea más fácil para alguien que va a tratar de convencer a IE8 para trabajar. Espero que IE8 muera horriblemente en una muerte dolorosa pronto.

ACTUALIZACIÓN:

Como sv_in señala, podría usar event.originalEvent para obtener el evento original objeto y establecer la propiedad returnValue en la original. Pero aún no lo he probado en mi IE8.

 11
Author: muffir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:18

Mootools redefine preventDefault en objetos de evento. Por lo tanto, su código debería funcionar bien en todos los navegadores. Si no lo hace, entonces hay un problema con el soporte ie8 en mootools.

¿Probaste tu código en ie6 y / o ie7?

El doc dice

Cada evento agregado con addEvent obtiene el método mootools automáticamente, sin la necesidad de instarlo manualmente.

Pero en caso de que no lo haga, es posible que desee probar

new Event(event).preventDefault();
 6
Author: Alsciende,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-16 10:26:16
if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

Probado en IE 9 y Chrome.

 3
Author: RolandoCC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-20 22:25:51

Para deshabilitar una tecla del teclado después de IE9, use: e.preventDefault();

Para desactivar una tecla de teclado regular bajo IE7 / 8, use: e.returnValue = false; o return false;

Si intentas desactivar un atajo de teclado (con Ctrl, como Ctrl+F) necesitas agregar esas líneas:

try {
    e.keyCode = 0;
}catch (e) {}

Aquí hay un ejemplo completo para IE7/8 solamente:

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Referencia: Cómo desactivar los atajos de teclado en IE7 / IE8

 3
Author: JBE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-14 15:27:19

Aquí está una función que he estado probando con jquery 1.3.2 y 09-18-2009 nightly build. Hazme saber tus resultados. Todo se ejecuta bien en este extremo en Safari, FF, Opera en OSX. Es exclusivamente para corregir un error IE8 problemático, y puede tener resultados no deseados:

function ie8SafePreventEvent(e) {
    if (e.preventDefault) {
        e.preventDefault()
    } else {
        e.stop()
    };

    e.returnValue = false;
    e.stopPropagation();
}

Uso:

$('a').click(function (e) {
    // Execute code here
    ie8SafePreventEvent(e);
    return false;
})
 2
Author: Eliran Malka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-20 22:27:20

preventDefault es un estándar muy extendido; usar un adhoc cada vez que desea cumplir con las versiones antiguas de IE es engorroso, mejor usar un polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

Esto modificará el prototipo del evento y agregará esta función, una gran característica de javascript/DOM en general. Ahora puede usar e.preventDefault sin ningún problema.

 1
Author: EliuX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-26 21:05:22

return false en su oyente debería funcionar en todos los navegadores.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}
 0
Author: daemon1981,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-05 10:37:11

FWIW, en caso de que alguien vuelva a visitar esta pregunta más tarde, también puede verificar lo que está entregando a su función de controlador onKeyPress.

Me encontré con este error cuando pasé por error onKeyPress(esto) en lugar de onKeyPress(evento).

Algo más para comprobar.

 0
Author: Kirby L. Wallace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-22 22:51:11

Me ayudó un método con una comprobación de función. Este método funciona en IE8

if(typeof e.preventDefault == 'function'){
  e.preventDefault();
} else {
  e.returnValue = false;
}
 0
Author: Pablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-16 11:37:15