简体   繁体   English

为什么 .on 函数在我的 JQuery 上不起作用

[英]Why wont the .on function work on my JQuery

I'm trying to write a jQuery function on a website that will launch a series of questions when a button os clicked, but when the button is clicked the prompts don't work.我正在尝试在网站上编写一个 jQuery 函数,该函数将在单击按钮 os 时启动一系列问题,但是当单击该按钮时,提示不起作用。

<script>

$('submit').on('click', function() {
    var username = prompt("Please type your username");
    var password = prompt("Please type your password");
    var welcome = alert("welcome " + username);
});

</script>

The 'submit' selector matches <submit> elements, i think you are looking for input[type="submit"] 'submit'选择器匹配<submit>元素,我想你正在寻找input[type="submit"]

 $('input[type="submit"]').on('click', function(){ var username = prompt("Please type your username"); var password = prompt("Please type your password"); var welcome = alert("welcome " + username); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <form> <input type="submit"/> </form> </body> </html>

You need to make sure that script is firing inside of a DOM Ready handler:您需要确保脚本在 DOM Ready 处理程序内触发:

$(function(){

Your code

});

You haven't provided a complete question here, but I noticed that 'submit' is not the name of a standard HTML element.您在这里没有提供完整的问题,但我注意到'submit'不是标准 HTML 元素的名称。 Therefore, I'm going to assume that it's either an ID or class name.因此,我将假设它是一个 ID 或类名。

If it's an ID, you should use '#submit' .如果是 ID,则应使用'#submit' If it's a class name, you should use '.submit' .如果是类名,则应使用'.submit'

Your jQuery selector is probably incorrect.您的 jQuery 选择器可能不正确。 $('submit') will look for a <submit> element in your HTML, which is probably not what you want. $('submit')将在您的 HTML 中查找<submit>元素,这可能不是您想要的。

My guess is that you are looking for a click on an <input type="submit"> , in which case you should use $('input[type="submit"]) and not $('submit')我的猜测是您正在寻找对<input type="submit"> ,在这种情况下,您应该使用$('input[type="submit"])而不是$('submit')

Make sure you put your script end of body Or use ready function if you have to put it on top of your page确保将脚本放在正文的末尾,或者如果必须将其放在页面顶部,请使用 ready 函数

$(document).ready(function () {
       // your code 
 });

Or youse above answer is it as same as ready function.或者你上面的答案是否与就绪函数相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM