[英]jQuery or javascript prevent event from input keypress
CODE: 码:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">') appender.find('#search_made').on('keypress', function(e) { e.preventDefault() console.log('keypress!') if (e.keyCode == 13 && !e.shiftKey) { console.log('not shift enter') var passed_value = $(this).val() if (passed_value === '') { console.log('nothing was passed on input tag') return false; } console.log('passed value: ' + passed_value) } }) $('body').append(appender)
I want to add input
tag dynamically by jQuery. 我想通过jQuery动态添加
input
标签。
Using those code, I can only add input tag seemingly but other functions that has to be bound was not bound well. 使用这些代码,我只能看似添加输入标记,但其他必须绑定的函数不能很好地绑定。
So when I type some words on input tag and click enter key
, It refreshes page but does not execute any console.log()
lines. 因此,当我在输入标签上键入一些单词并单击
enter key
,它会刷新页面但不会执行任何console.log()
行。
How can I fix it to make it do other bound functions(include console.log()
) well? 如何修复它以使其执行其他绑定功能(包括
console.log()
)?
Change the selector from: 更改选择器:
appender.find('#search_made').on('keypress', function(e) {
To 至
$(document).on('keypress','#search_made', function(e) {
OR: Simply 或者:简单
appender.on('keypress', function(e) {
Working Code Example: 工作代码示例:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">') $(document).on('keypress','#search_made', function(e) { e.preventDefault() console.log('keypress!') if (e.keyCode == 13 && !e.shiftKey) { console.log('not shift enter') var passed_value = $(this).val() if (passed_value === '') { console.log('nothing was passed on input tag') return false; } console.log('passed value: ' + passed_value) } }) $('body').append(appender)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.