【问题标题】:.on() function not working for Ajax Loaded Form in Bootstrap Modal.on() 函数不适用于 Bootstrap 模式中的 Ajax 加载表单
【发布时间】:2012-09-18 03:46:18
【问题描述】:

所以我通过在 index.html 中执行以下操作来加载表单。

 $(".add-cell").click(function(ev) { // for each edit contact url
        ev.preventDefault(); // prevent navigation
        var url = $(this).data("form"); // get the contact form url
        $("#cell-modal").load(url, function() { // load the url into the modal
            $(this).modal('show'); // display the modal on url load
        });
        return false; // prevent the click propagation
    });

这会加载位于文件 add.html 中的表单。这是表格:

 <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>{{l_name}}, <small>new cell</small></h3>
 </div>
 <div class="modal-body">
    <form class="cell-form" action="/cells/add/{{l_name}}/{{l_id}}/" method="post">   
     {% csrf_token %}
     {{ cell_form.as_table }}
     </form>
 </div>
 <div class="modal-footer">
     <input class="btn btn-success submit" type="submit" id="cell_submit" value="Submit" />
     <input type="button" name="cancel" class="btn btn-danger" data-dismiss="modal" value="Close"/>
 </div>

现在,在我的 index.html 中有以下代码:

 $('.cell-form').on('submit', function() {
        $.ajax({ 
            type: $(this).attr('method'), 
            url: this.action, 
            data: $(this).serialize(),
            context: this,
            success: function(data, status) {
               //Do stuff
            }
        });
        return false;
    });

此代码有效,并且此脚本位于 index.html 中,而不是 add.html 中。但是,为什么在 add.html 中的按钮放在 index.html 中时,这段代码不起作用?:

    $("#cell_submit").on('click', function(event){
        alert("LOL");
    });

我想将我的 JS 放在 index.html 中...而不是 add.html 中。

谢谢!

【问题讨论】:

    标签: javascript jquery django twitter-bootstrap


    【解决方案1】:

    您附加事件的元素必须存在于 DOM 中。你需要使用这样的东西

    $("#cell_modal").on('click', '#cell_submit', function(event){
        alert("LOL");
    });
    

    有关这方面的更多信息,请查看直接和委托事件here

    部分

    【讨论】:

      【解决方案2】:

      您需要首先选择文档。它应该是这样的:

      $(document).on('click', '#cell_submit', function(event){
          alert("LOL");
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多