jQuery 元素上的绑定事件失败

jQuery bind event on element fails

我们正在使用 jQuery 2.1.4 并编写了自己的 JavaScript class 来处理事件。这是一个非常简单的“应用程序”。它所做的只是负责提交表单。在此之前,它处理数据。

我们在呈现页面时调用的初始方法:

OWebForm.prototype.init = function(){
    console.log("init Method called");

    ...
    $("#submit_message").on("click", this._submit);
    console.log($("#submit_message"));
    ...
}
OWebForm.prototype._submit = function(e){
    e.preventDefault();
    console.log("_submit Method called");
...
    }

单击按钮“#submit_message”后,应该会调用OWebForm class 的_submit 方法。当查看控制台中的元素时,我可以看到它在加载页面时没有绑定到任何东西。因此,一旦单击按钮,代码就不会执行。

在HTML中我有以下代码:

<script type="text/Javascript">
        var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");       
        _oWebForm.init();
    </script>

根据我了解到的文档,该函数必须存在才能绑定到元素事件。使用对象时不是这种情况吗?我该如何解决这个问题?

这对我有用:

var OWebForm = function(a){

};
OWebForm.prototype.init = function() {
  alert("init Method called");

  $("#submit_message").on("click", this._submit);
}
OWebForm.prototype._submit = function(e){
  e.preventDefault();
  alert("_submit Method called");
}
$(function() {
  var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");
  _oWebForm.init();
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>

<form id="myFrm">
    <input type="text">
    <input id="submit_message" type="submit" value="Click me To test">
</form>

您需要替换:

$("#submit_message").on("click", this._submit);

与:

$(document).on("click", "#submit_message", this._submit);

如果 submit_message 尚未加载!

您的脚本在 DOM 加载之前执行,因此该元素尚不存在,并且 jQuery 选择器不匹配任何内容,因此没有元素获得绑定到的点击处理程序他们。您需要在 $(document).ready().

中调用 init() 方法

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

$(document).ready(function() {
    var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");
    _oWebForm.init();
});