代码:
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)
我想通过 jQuery 动态添加 input
标签。
使用这些代码,我似乎只能添加输入标签,但其他必须绑定(bind)的功能并没有绑定(bind)好。
因此,当我在输入标签上键入一些词并单击 enter key
时,它会刷新页面但不会执行任何 console.log()
行。
我怎样才能修复它以使其能够很好地执行其他绑定(bind)功能(包括 console.log()
)?
最佳答案
更改选择器:
appender.find('#search_made').on('keypress', function(e) {
到
$(document).on('keypress','#search_made', function(e) {
或者:简单地
appender.on('keypress', function(e) {
工作代码示例:
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>
关于javascript - jQuery 或 javascript 阻止输入按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52649635/