【问题标题】:javascript on the main page is not working in the dynamically loaded content主页上的 javascript 在动态加载的内容中不起作用
【发布时间】:2016-04-13 04:38:42
【问题描述】:

我正在通过 ajax get 将内容加载到一个 div 中,我有 3 个页面:

索引 通过ajax加载的动态内容 javascript.js

现在当我通过以下方式将数据加载到索引中时:

$.ajax({
   url: target,
   type: 'GET', 
}).done(function(data)
{
  $(".modal-content").html($(data).find('.inner_modal'));
  $(".modal-header").prepend('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>');
 });
 });

即使我在主索引中包含了 javascript 文件,javascript 也无法使用它。

我试过这样绑定:

$(function()
{
    $('.inner_modal').on("submit", "#account-login-form", function()
    {
        $('.ajloading').show();
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            dataType: 'json',
            data: $(this).serialize(),
            success: function(data)
            {
                if(!data.success)
                {
                    $('#error_message').html(data.error + alert_close).show();
                }else{
                    <?php if(Session::get('refer') == true &&  Session::get('refer') != 'user/logout'): ?>
                        window.location.href = '<?php echo Config::get('URL'); ?><?php echo System::escape(Session::get('refer')); ?>';
                    <?php else: ?>
                        window.location.href = '<?php echo Config::get('URL'); ?>dashboard';
                    <?php endif; ?>
                }
                $('.ajloading').hide();
            }, error: function(data)
            {
                $('.ajloading').hide();
            }
        });
        return false;
    });
});

我试过这样:

$(document).on("submit", "#account-login-form", function()

我也试过没有

$(function(){});

现在,当我在动态加载的内容中取消包含 javscript 文件时,它可以工作,但我不能对每个文件都这样做,而且它会使我的脚本膨胀,所以我该如何解决这个问题,以便动态内容与我的主要内容一起工作js 文件....这是我的做法:

<body>
    <div class="modal-content">
        <!-- dynamic content loaded !-->
    </div>
</body>

<script>
    $.ajax({
       url: target,
       type: 'GET', 
    }).done(function(data)
        {
          $(".modal-content").html($(data).find('.inner_modal'));
          $(".modal-header").prepend('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>');
        });
    });
</script>
<script src="myjs.js"></script>
</html>

【问题讨论】:

  • “不工作”是什么意思——是代码渲染到页面而不是“触发”——还是没有渲染到页面?您是否在控制台中遇到任何错误?另外,请查看之前的答案:stackoverflow.com/questions/3619484/…
  • defering 你的脚本怎么样? async vs defer
  • @timster 它没有触发,但它在我的主脚本的页脚中,所以它在那里并且没有控制台错误。
  • PHP 代码在那里做什么?这实际上会在发送到浏览器的 JavaScript 中吗?如果是这样,那将不起作用,因为服务器永远不会解释 PHP。 (您是否检查过您的 HTML 中是否存在未解释的 PHP?)

标签: javascript jquery


【解决方案1】:

我认为您的问题是“提交”不是冒泡的事件。您应该在通过 ajax 加载表单后直接为其分配一个点击处理程序。

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多