我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。
当按下回车键时,如何防止表单被提交?
当前回答
我使用了document on,它涵盖了页面加载后动态添加的html:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
增加来自@Bradley4的更新
其他回答
react js解决方案
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
原生js(获取api)
document.onload = (() => { alert('ok'); let keyListener = document.querySelector('#searchUser'); // keyListener.addEventListener('keypress', (e) => { if(e.keyCode === 13){ let username = e.target.value; console.log(`username = ${username}`); fetch(`https://api.github.com/users/${username}`,{ data: { client_id: 'xxx', client_secret: 'xxx' } }) .then((user)=>{ console.log(`user = ${user}`); }); fetch(`https://api.github.com/users/${username}/repos`,{ data: { client_id: 'xxx', client_secret: 'xxx' } }) .then((repos)=>{ console.log(`repos = ${repos}`); for (let i = 0; i < repos.length; i++) { console.log(`repos ${i} = ${repos[i]}`); } }); }else{ console.log(`e.keyCode = ${e.keyCode}`); } }); })(); <input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
使用两个事件。which和event.keyCode:
function (event) {
if (event.which == 13 || event.keyCode == 13) {
//code to execute here
return false;
}
return true;
};
我使用了document on,它涵盖了页面加载后动态添加的html:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
增加来自@Bradley4的更新
重写表单的onsubmit动作,调用你的函数,并在后面添加return false,即:
<form onsubmit="javascript:myfunc();return false;" >