事件处理程序不在外部JS文件中工作?

时间:2017-03-02 08:12:14

标签: javascript php jquery html ajax

这有效:(将所有内容保存在一个文件中)

<html><head></head>
    <body>
    //content-wrapper --> ajax loaded
    <script type="text/javascript">
        $(document).ajaxComplete(function(event, xhr, settings) {
            var a_row_id = 0;
            $('body').on('click', '.ready-create-rename-row', function() {
                a_row_id = $(this).data('row-id');
                console.log('Attempting to rename row ' + a_row_id);
            });
        });
    </script>      
    </body>
</html>

这并不是:我没有收到任何错误,但事件处理程序没有触发;控制台保持空白

<html><head></head>
    <body>
    <!-- content-wrapper -- ajax loaded -->        
    <script src="<?php echo base_url();?>assets/js/func_rows.js" type="text/javascript"></script>
    <script type="text/javascript">
       //Some code in document.ready
    </script>      
    </body>
</html>

func_rows.js:

$(document).ajaxComplete(function(event, xhr, settings) {
    var a_row_id = 0;
    $('body').on('click', '.ready-create-rename-row', function() {
        a_row_id = $(this).data('row-id');
        console.log('Attempting to rename row ' + a_row_id);
    });
    //Other events here get fired however
});

Ajax加载的内容:

<div class="row-options">
    <button type="button" class="flat circle ready-create-rename-row" 
                 data-row-id=<?php echo $r->id; ?>
                 data-label-id='row_rename_<?php echo $r->id; ?>' 
                 data-toggle="modal" 
                 data-target="#rename-row-modal">
                 <i class="mdi mdi-pencil"></i>
    </button>
</div>

<!-- Rename Row Confirmation Modal -->
<div id="rename-row-modal" class="modal fade" role="dialog">
    <div class="modal-dialog plain-material-dialog confirmation">
      <!-- Modal content-->
      <div class="modal-content plain-material-content">
        <div class="modal-body plain-material-body">
                Rename Row
        <div class="material-input-group stretched">
                    <label>Row name</label>
                    <input type="text" id="create-new-row-name" required>
                </div>
        </div>
        <div class="modal-footer plain-material-footer">
          <button type="button" class="btn btn-default flat" data-dismiss="modal">cancel</button>
          <button type="button" class="btn btn-default flat" id="create-rename-row">rename</button>
        </div>
      </div>
    </div>
</div>

让我感到困惑的是,ajaxCompletefunc_rows.js中的其他事件处理程序即使被绑定到加载了ajax的元素也会被触发。我期待的是,当您点击带有.ready-create-rename-row的按钮时,控制台中会弹出一条消息,但没有任何反应。但是当我将事件处理程序放在同一个html文件中(作为模板)时,它可以工作。

1 个答案:

答案 0 :(得分:0)

原来,罪魁祸首是ajaxComplete处理程序中的另一种方法:

$('body').off().on('click', '.rename-row' function()
{
   //stuff

    $.ajax({
     //Stuff
    });
 });

.off()基本上禁用了之前发生的所有事件,因此我必须将其置于顶部并将'body'更改为类.rename-row'以使其更加安全