简体   繁体   English

启用Enter fire JavaScript功能

[英]On Enter fire javascript function

After reading this post here in Stackoverflow, ( Detect the Enter key in an text input field ) I tried to make a few of my inputs fire on enter... I did not work. 在Stackoverflow上阅读了这篇文章之后,( 在文本输入字段中检测出Enter键 ),我试图使输入中的一些内容在Enter上触发...我没有用。 I made a simple example and it still doesn't work. 我举了一个简单的例子,它仍然行不通。 Can someone hint as to the proper way? 有人可以暗示正确的方法吗? (FYI - Definitely a newbie here) (仅供参考-这里绝对是新手)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>On Enter</title>

<script src="../../Scripts/jquery-2.1.0.min.js"></script> 
<script>
        $(".input1").keyup(function (e) {
            if (e.keyCode == 13) {
                alert ("It Works");
            }
        });
</script>

</head>

<body>


        <input type="text"
            id="input1"
            placeholder="Press Enter When Done">
        </input>


</body>
</html>

Thanks 谢谢

First you need to say #input1 other than .input1 , then run it when the entire DOM is ready: 首先,您需要说#input1而不是.input1 ,然后在整个DOM准备就绪时运行它:

$(document).ready(function(){
    $("#input1").keyup(function (e) {
        if (e.keyCode == 13) {
            alert ("It Works");
        }
    });
});

Edit : As @jfriend00 mentioned in a comment it's a good idea to use e.which other than e.keycode . 编辑 :作为@ jfriend00在评论中提到它的使用是一个好主意e.which以外e.keycode To do so you can change: e.keyCode == 13 to e.which == 13 . 为此,您可以将e.keyCode == 13更改为e.which == 13 This way is recommenced by the people at jQuery, as it normalizes e.keyCode and e.charCode . jQuery的人们推荐这种方式,因为它规范了e.keyCodee.charCode

Change the .input1 in your JS to #input1 将JS中的.input1更改为#input1

When you use . 使用时. it means it's a class, but you have an ID, which is # . 这意味着它是一个类,但是您有一个ID,即#

Your code is triggering a "class", not an "id", so add a "#" instead of a "." 您的代码正在触发“类”,而不是“ id”,因此请添加“#”而不是“”。 in input1: 在输入1中:

       $("#input1").keyup(function (e) {
            if (e.keyCode == 13) {
                alert ("It Works");
            }
        });

first, like the previous answer your criteria is not good. 首先,像上一个答案一样,您的条件不好。 change for ID second, put your javascript at the and of the file on in the ready document. 更改ID为第二,将您的javascript放在就绪文档中的和上。 Because the javascript is in execution while the documenta as not finish to load . 因为JavaScript正在执行,而documenta尚未完成加载。 So the event can't be add to an element that doesnt exist. 因此,无法将事件添加到不存在的元素中。

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

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