在窗体内部单击jQuery句柄按钮

jQuery handle button click inside a form

本文关键字:句柄 按钮 jQuery 单击 窗体 内部      更新时间:2024-07-01

我不明白为什么我的jQuery代码无法访问表单中的按钮。

<form action="">
    <div class="field">
        <label for='username'>Insert username</label>
        <input type="text" id="username" name="username">
    </div>
    <button type='submit' class='btn btn-lg btn-primary buttonRegister'>Register</button>
</form>

以下是我的jQuery点击尝试代码:

$('.buttonRegister').submit(function(){  
    //action inside function
});

--------------或------------------------

$('.buttonRegister').click(function(){  
    //action inside function
});

--------------或------------------------

$('.buttonRegister').on("click", function(){  
    //action inside function
});

它们都不起作用。我确信click函数内部的代码是有效的,因为我试图在表单外部获取按钮,它运行得很好。

在内部添加e.preventDefault()。

$('.buttonRegister').on("click", function(e){  
   e.preventDefault(); // <<-- required to stop the refresh
   //action inside function
});