Javascript 不会通过动态加载的表单和脚本触发

发布于 2025-01-09 14:16:15 字数 1967 浏览 1 评论 0原文

我正在通过 .ajax 将表单和随附的 JS 脚本加载到模式中,但 JS 没有按预期触发或初始化元素。 (没有任何反应)HTML 和脚本在其他地方按预期工作,除非通过 ajax 加载到模式中。

以下是我如何使用 Promise 加载内容,以确保仅在加载 HTML 后才加载脚本。有什么指示我可能会出错吗?

$(document).on('click', '#post-offer', function() {
        $.when(
              $('head').append('<link rel="stylesheet" href="' + baseURL + '/css/jquery-ui.css">'),
            $('head').append('<link rel="stylesheet" href="' + baseURL + '/css/jquery.tagit.css">'),
            $('head').append('<link rel="stylesheet" href="' + baseURL + '/slim/slim.min.css">'),
            $.getScript( "//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"),
            openModal(baseURL + '/ajax.cgi?a=showoffer'), // << THIS IS THE HTML FORM
            $.Deferred(function(deferred){
                $(deferred.resolve);
            })
        ).done(function(){
            $.getScript( "//maps.googleapis.com/maps/api/js?v=3&key=xxxxxxxxxxxxxx"),
            $.getScript( baseURL + "/js/tag-it.js" ),
            $.getScript( baseURL + "/slim/slim.jquery.js" ),
            $.getScript( baseURL + "/js/listing.js" );
            
        });
});

为了完整起见,这是 openModal 函数(按预期工作):

function openModal(arg) {
    $('#loading').show();
    if (arg.match(/^http/)) { //If query, then send it.
        var $query = arg;
        $.ajax({
            url: $query,
            success: function(result) {
                $('#modalWrap').show();
                $('#modalContent').html(result);
                $('#loading').hide();
            },
            error: function(xhr) {
                $("#loading").hide();
                alert('Communication error! [Details: ' + xhr.status + ' - ' + xhr.statusText + ']');
            }
        });
    } else { //Or just return the input argument
        $('#modalWrap').show();
        $('#modalContent').html(arg);
        $('#loading').hide();
    };
};

I'm loading a form and accompanying JS scripts into a modal via .ajax, but the JS isn't firing or initialising the elements as expected. (Nothing happens) The HTML and scripts work as expected elsewhere except when loaded via ajax into a modal.

Here's how I'm loading the content using a Promise to make sure and load the scripts only after the HTML is loaded. Any pointers where I may be going wrong?

$(document).on('click', '#post-offer', function() {
        $.when(
              $('head').append('<link rel="stylesheet" href="' + baseURL + '/css/jquery-ui.css">'),
            $('head').append('<link rel="stylesheet" href="' + baseURL + '/css/jquery.tagit.css">'),
            $('head').append('<link rel="stylesheet" href="' + baseURL + '/slim/slim.min.css">'),
            $.getScript( "//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"),
            openModal(baseURL + '/ajax.cgi?a=showoffer'), // << THIS IS THE HTML FORM
            $.Deferred(function(deferred){
                $(deferred.resolve);
            })
        ).done(function(){
            $.getScript( "//maps.googleapis.com/maps/api/js?v=3&key=xxxxxxxxxxxxxx"),
            $.getScript( baseURL + "/js/tag-it.js" ),
            $.getScript( baseURL + "/slim/slim.jquery.js" ),
            $.getScript( baseURL + "/js/listing.js" );
            
        });
});

For completeness, here's the openModal function (which works as expected):

function openModal(arg) {
    $('#loading').show();
    if (arg.match(/^http/)) { //If query, then send it.
        var $query = arg;
        $.ajax({
            url: $query,
            success: function(result) {
                $('#modalWrap').show();
                $('#modalContent').html(result);
                $('#loading').hide();
            },
            error: function(xhr) {
                $("#loading").hide();
                alert('Communication error! [Details: ' + xhr.status + ' - ' + xhr.statusText + ']');
            }
        });
    } else { //Or just return the input argument
        $('#modalWrap').show();
        $('#modalContent').html(arg);
        $('#loading').hide();
    };
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以可爱出名 2025-01-16 14:16:15

尝试将其替换为您的 openModal 函数:

function openModal(arg) {
  return new Promise((resolve, reject) => {
    $("#loading").show();
    if (arg.match(/^http/)) {
      //If query, then send it.
      var $query = arg;
      $.ajax({
        url: $query,
        success: function (result) {
          $("#modalWrap").show();
          $("#modalContent").html(result);
          $("#loading").hide();
          resolve();
        },
        error: function (xhr) {
          $("#loading").hide();
          alert(
            "Communication error! [Details: " +
              xhr.status +
              " - " +
              xhr.statusText +
              "]"
          );
          reject()
        },
      });
    } else {
      //Or just return the input argument
      $("#modalWrap").show();
      $("#modalContent").html(arg);
      $("#loading").hide();
      resolve();
    }
  });
}

如果仅此方法没有帮助,请在添加上面的代码后将 done 替换为此函数:

done(function () {
  window.requestAnimationFrame(() => {
    $.getScript("//maps.googleapis.com/maps/api/js?v=3&key=xxxxxxxxxxxxxx");
    $.getScript(baseURL + "/js/tag-it.js");
    $.getScript(baseURL + "/slim/slim.jquery.js");
    $.getScript(baseURL + "/js/listing.js");
  });
});

try replacing this with your openModal function:

function openModal(arg) {
  return new Promise((resolve, reject) => {
    $("#loading").show();
    if (arg.match(/^http/)) {
      //If query, then send it.
      var $query = arg;
      $.ajax({
        url: $query,
        success: function (result) {
          $("#modalWrap").show();
          $("#modalContent").html(result);
          $("#loading").hide();
          resolve();
        },
        error: function (xhr) {
          $("#loading").hide();
          alert(
            "Communication error! [Details: " +
              xhr.status +
              " - " +
              xhr.statusText +
              "]"
          );
          reject()
        },
      });
    } else {
      //Or just return the input argument
      $("#modalWrap").show();
      $("#modalContent").html(arg);
      $("#loading").hide();
      resolve();
    }
  });
}

if that alone didn't help, replace done with this after you added the code above:

done(function () {
  window.requestAnimationFrame(() => {
    $.getScript("//maps.googleapis.com/maps/api/js?v=3&key=xxxxxxxxxxxxxx");
    $.getScript(baseURL + "/js/tag-it.js");
    $.getScript(baseURL + "/slim/slim.jquery.js");
    $.getScript(baseURL + "/js/listing.js");
  });
});
萌能量女王 2025-01-16 14:16:15

以下是我为其他遇到此问题的人解决的方法。

这不是加载问题。所有脚本和 HTML 均加载良好。问题是,动态加载的脚本之一 listing.js 有一个 document.ready() 包装器,由于 DOM 已经加载,所以它没有触发,因此 JS 元素动态加载的表单没有被初始化。但是,当我删除 document.ready() 时,它仍然没有初始化动态加载的元素。

为了解决这个问题,我将 document.ready() 更改为函数 initialize() 并从动态加载的 HTML 中最后调用该函数。现在一切正常:

//DYNAMICALLY LOADED SCRIPT FIRST    
function initialize(){

    //INITIALIZE JS FORM ELEMENTS...

    }

然后,在同一个 AJAX 调用中:

<form class="dynamically-loaded-HTML">

<!-- FORM ELEMENTS -->

</form>
<script>
initialize();
</script>

Here's how I solved it for anyone else with this problem.

It wasn't a loading problem. All the scripts and HTML loaded fine. The problem was that one of the dynamically loaded scripts listing.js had a document.ready() wrapper which wasn't firing since DOM was already loaded, so JS elements on the dynamically-loaded form weren't being initialized. However, when I removed the document.ready(), it still wasn't initializing the dynamically-loaded elements.

To get around this, I changed the document.ready() to a function initialize() and called that last from the dynamically-loaded HTML. It all works fine now:

//DYNAMICALLY LOADED SCRIPT FIRST    
function initialize(){

    //INITIALIZE JS FORM ELEMENTS...

    }

Then, in the same AJAX call:

<form class="dynamically-loaded-HTML">

<!-- FORM ELEMENTS -->

</form>
<script>
initialize();
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文