1
這工作:(保持它都在同一個文件)事件處理程序不在外部JS文件中工作?
<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>
什麼是困惑我的是,在func_rows.js
ajaxComplete
其他事件處理程序被解僱,即使他們'綁定到ajax加載的元素。我期望的是,當你點擊按鈕.ready-create-rename-row
時,控制檯中會彈出一條消息,但沒有任何反應。但是,當我把事件處理程序放在同一個html文件(作爲模板)時,它就可以工作。
爲什麼還要在附加委託事件處理函數時使用'$ .ajaxComplete()'?所有這些都會在後續請求中複製處理程序 –
我認爲我需要它用於加載Ajax的內容。所以刪除它可以嗎? – herondale
絕對沒問題。只需使用委託事件處理程序本身 –