javascript - 使用 Ajax 调用修改 DOM 后 JS 函数不起作用
问题描述
我有一个模式,其中内容由 Ajax 调用加载。
Ajax调用将一个新的表单加载到模态体中,我需要在这个表单上使用一些js插件(显示地图,使用TinyMCE,Chosen.js等)
我尝试了很多我在其他帖子中读到的东西,但没有一个对我有用......
// Performs a lot of things
function init() {
$('.chosen').chosen();
$('.toggleswitch').bootstrapToggle();
tinymce.init();
}
// Long Google Maps function
function initAutocomplete() {
// a lot of code
}
// Another Google Maps function
function fillInAddress() {
// a lot of code
}
//The problematic function
$('#modalEditLieu').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var lieu_id = button.data('lieu-id');
$("#modalEditLieu .modal-body").html('').addClass('loading');
$.get( "/lieux/" + lieu_id + "/edit", function( data ) {
// Here I fill modal body with html send by ajax call
$("#modalEditLieu .modal-body").html(data).removeClass('loading');
// I tried to call functions again here
init();
initAutocomplete;
fillInAddress();
// I also tried to put it in
// $("#modalEditLieu .modal-body").html(data).promise().then(...)
// as suggested in some posts
});
});
// I call all the functions in here
$('document').ready(function () {
init();
initAutocomplete;
fillInAddress();
});
// I tried to call it in the ajaxComplete event as suggested but it does not work
$( 'document' ).ajaxComplete(function() {
init();
initAutocomplete;
fillInAddress();
});
我知道在第一次加载时调用的函数是基于第一个 DOM 的,它们不适用于动态加载的 html。
但是我尝试了很多不同的方法并阅读了很多但我无法让它工作......
解决方案
推荐阅读
- python - 如何使用 PANDAS 过滤掉一行?
- excel - Excel中的Sumifs与日期计算
- quire-api - 如何在 Quire 应用中接受用户配置?
- c# - 网络框架上的包引用不加载传递依赖项(未在输出中复制)
- swift - 如果按下按钮,则仅在 for 循环内继续
- reactjs - 在反应中通过主题提供者的材料 UI 多种字体
- python - 将列名中的字符串转换为 Pandas 中的 DateTime 对象
- date - 火花年龄计算间隔数据类型
- python-3.x - 通过文件夹中的上下文菜单打开 Powershell 时出现错误消息
- aws-lambda - API Gateway 400 在到达我的代码/lambda 之前