在 buttonclick 上调用 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13974101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:09:05  来源:igfitidea点击:

Call jQuery on buttonclick

jquery

提问by KristianMedK

I'm trying to run some jQuery code when I click a button, but I can't make even the most simple example work.

我试图在单击按钮时运行一些 jQuery 代码,但即使是最简单的示例也无法运行。

My jQuery code is this:

我的 jQuery 代码是这样的:

<script src="scripts/jquery-1.4.1.js"></script>
<script>
    $('#btn').click(function() {
        alert("Hello");
    });

</script>

and my html looks like this

我的 html 看起来像这样

    <div>
        <input id="btn" type="button" value="button" />
    </div>

but when I click the button nothing happens.

但是当我点击按钮时什么也没有发生。

回答by ?????

wrap your code inside a document.ready function

将您的代码包装在一个 document.ready 函数中

$(function(){
    $('#btn').click(function() {
        alert("Hello");
    });
});

or put your script code right before the end of the body tag

或将您的脚本代码放在 body 标记的末尾之前

You need to wait for the elements to be available the dom on page load before binding event handlers

在绑定事件处理程序之前,您需要等待元素在页面加载时可用

回答by Doink

Try the following

尝试以下

$(function(){
    $('#btn').on('click', function(){
       alert('click event');
    });
});

If this does not work make sure you included jquery correct.

如果这不起作用,请确保您正确地包含了 jquery。

If you are unsure try the following.

如果您不确定,请尝试以下操作。

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>

回答by Per Salbark

Try binding the event after the DOM has loaded.

尝试在 DOM 加载后绑定事件。

$(document).ready(function() {
    $('#btn').click(function() {
        alert("Hello");
    });
});

回答by Anujith

Try your function in:

试试你的功能:

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

回答by Anujith

Try to code with document when ready

准备好后尝试用文档编码

$(document).ready(function() {
  $('#btn').click(function() {
    alert("Hello");
  });
});