简体   繁体   English

preventDefault()不在输入类型文本中工作

[英]preventDefault() not working in a input type text

This is my code: 这是我的代码:

$('#Login').keydown(function(e){         
        if(e.which  == 32){     
            alert("enter");
            this.preventDefault();            
        }        
    });

This code doesn't work but sends the alert 此代码不起作用,但发送警报

$('#Pwd,#Pwd2').on('keydown',function(e){
        if(e.which == 32){
            e.preventDefault();
        }
    });

And this code works. 这段代码有效。 I do not understand why. 我不理解为什么。

You are wanting to prevent the default action of the Event (which is passed in as the parameter for your event function, you are calling it e ). 您希望阻止Event的默认操作(作为事件函数的参数传入,您将其称为e )。

this is the element that is the target of your event (ie: in this case e.target which will be your #Login element) and not an event itself, this does not have a preventDefault() . this是您的事件的目标元素(即:在这种情况下, e.target将是您的#Login元素)而不是事件本身,它没有preventDefault()

Just use the Event object for this as well: 只需使用Event对象:

$('#Login').keydown(function(e){         
    if(e.which == 32){     
        e.preventDefault();            
    }        
});

With the above you'll see the event is cancelled every time you hit the space bar within #Login : http://jsfiddle.net/xWmUU/ 有了上述内容,您每次看到#Login的空格键时都会看到该事件被取消: http//jsfiddle.net/xWmUU/

preventDefault is a method of the Event object, so it makes sense that it works when called on an event. preventDefault是Event对象的一个​​方法,因此在事件调用时它有效。

this will refer to #Login in this case, which is a DOM object and will not have the preventDefault method. 在这种情况下, this将引用#Login ,它是一个DOM对象,不具有preventDefault方法。

Note that because of how event propagation works, this will not always be equal to e.target . 请注意,由于事件传播是如何工作的, this并不总是等于e.target

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

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