gpt4 book ai didi

javascript - onclick 按钮不调用函数

转载 作者:行者123 更新时间:2023-11-30 11:32:04 28 4
gpt4 key购买 nike

我目前遇到的问题之一是无法调用提交按钮的 onclick 事件中的函数。

$(document).ready(function() {
function validate() {
var contactName = document.getElementById("contact-name").value;
alert("Thank you " + contactName);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="name">NAME</label>
<input id="contact-name" name="name" placeholder="Please enter your name..." type="text">
<label for="email">EMAIL</label>
<input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text">
<label for="email">MESSAGE</label>
<textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea>
</form>

<button type="button" id="submit" onclick="validate();">SUBMIT MESSAGE</button>

最佳答案

您应该将 validate() 函数编写为 $(document).ready 作为 onclick在绑定(bind) DOM 加载时 - 而 $(document).ready scopes 函数。

这意味着该函数对于闭包而言是本地,如果它在$(document ).准备好了.

请看下面的演示:

function validate() {
var contactName = document.getElementById("contact-name").value;
alert("Thank you " + contactName);

}
<form>
<label for="name">NAME</label>
<input id="contact-name" name="name" placeholder="Please enter your name..." type="text">
<label for="email">EMAIL</label>
<input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text">
<label for="email">MESSAGE</label>
<textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea>
</form>

<button type="button" id="submit" onclick="validate();">SUBMIT MESSAGE</button>

关于javascript - onclick 按钮不调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867078/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com