简体   繁体   English

JavaScript / jQuery事件未触发

[英]JavaScript/jQuery event not firing

Some parts of my code that could be useful: In 'index.php' 我的代码中可能有用的某些部分:在“ index.php”中

<link rel="stylesheet" href="/0/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="/0/0.css" />
<script src="/0/bootstrap/js/bootstrap.min.js"></script>
<script src="/0/js/jquery.min.js"></script>
<script src="contact.js"></script>
(...)
<input id="firstname" (...)"/>

(jQuery is version 2.0.3 and Bootstrap 2.3.2) (jQuery是2.0.3版和Bootstrap 2.3.2版)

In 'contact.js' 在“ contact.js”中

$('#firstname').bind('keyup keypress change keydown oninput input', function(e) {
    alert('test');
    alert($(this).val()); 
});

It looks like something very simple but I'm not so use to JavaScript and can't find out why the event is not firing when I type in the input. 看起来很简单,但是我不太习惯JavaScript,无法弄清为什么在输入时无法触发该事件。

Looks like the script is not in a dom ready handler, so when the script is executed the element may not be present in the dom structure that could be the reason 看起来脚本不在dom准备就绪处理程序中,因此执行脚本时,该元素可能不存在于dom结构中,这可能是原因

You need to add the script in dom ready handler 您需要在dom ready处理程序中添加脚本

jQuery(function(){
    $('#firstname').bind('keyup keypress change keydown oninput input', function(e) {
        alert('test');
        alert($(this).val()); 
    });
})

Using bind is not recommended. 不建议使用bind Try on : 尝试on

$(document).on('keyup keypress change keydown oninput input','#firstname', function(e) {
    alert('test');
    alert($(this).val()); 
});

If you delegate the event to document, this should work without waiting for the DOM loaded. 如果将事件委托给文档,则该方法无需等待DOM加载即可工作。 Or you could wait for the DOM fully loaded as pointed out by @Arun P Johny and use direct event: 或者,您可以等待@Arun P Johny指出的DOM完全加载,然后使用直接事件:

$('#firstname').on('keyup keypress change keydown oninput input', function(e) {
        alert('test');
        alert($(this).val()); 
    });

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

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