简体   繁体   English

单击后执行jQuery函数

[英]Execute jQuery function after clicking <button>

I am struggling with the following piece: 我正在努力处理以下内容:

<script>
$('button').click(function(){
alert("button clicked");
});
</script>

<button type="button" class="button-save">Save</button>

I do not get an alert when I click the button. 单击按钮时没有收到警报。 I tried targeting the class with the button, but that didn't help either. 我尝试使用按钮定位课程,但这也无济于事。 I am trying to execute some ajax (not in my example of course) when I click the Save button like in this answer, so I need to find when the user clicked the button. 当我像这个答案一样单击“保存”按钮时,我试图执行一些ajax(当然不是我的示例),因此我需要查找用户单击按钮的时间。

Can anyone help? 有人可以帮忙吗?

You have to wait until your page is completely rendered to bind handlers, else the elements dont exist yet. 您必须等待页面完全呈现以绑定处理程序,否则元素尚不存在。 You have two options, move your script tags to after your HTML has been rendered: 您有两个选择,可在呈现HTML之后将script标签移动到:

<button type="button" class="button-save">Save</button>

<script>
    $('button').click(function(){
        alert("button clicked");
    });
</script>

Or wrap your code in a DOM ready statement. 或将代码包装在DOM ready语句中。

<script>
    $(document).ready(function() {
        $('button').click(function(){
            alert("button clicked");
        });
    });
</script>

<button type="button" class="button-save">Save</button>

add this line in the head section of your html page 在您的html页面的头部添加此行

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

and rewrite your code to: 并将代码重写为:

$( document ).ready(function() {
   $('button').click(function(){
       alert("button clicked");
   });
});

You need to wrap your code like so: 您需要像这样包装代码:

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

The above basically says, "Target the document and all its elements once it's loaded and ready to go. Then execute your code." 上面的代码基本上说:“将文档及其所有元素加载到文档中并准备好运行。然后执行代码。”

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

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