1

因此,我通过在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 中。

谢谢!

4

2 回答 2

1

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

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

有关这方面的更多信息,请在此处查看直接和委托事件部分

于 2012-09-26T13:41:58.713 回答
1

您需要首先选择文档。它应该如下所示:

$(document).on('click', '#cell_submit', function(event){
    alert("LOL");
});
于 2013-06-01T01:30:41.340 回答