【问题标题】:Jquery load() doesn't load script tags in divJquery load() 不会在 div 中加载脚本标签
【发布时间】:2016-03-20 00:05:50
【问题描述】:

页面 1 有一个 ID 为 (#navigation) 的菜单,一个名为 Page2 的链接和一个 ID 为 (global_content) 的 DIV,当点击链接 Page2 时显示内容。在同一页面(第 1 页)中,我编写了一个 jquery 加载函数,这样当我单击链接时,它应该显示内容而无需重新加载页面。加载事件工作正常,显示内容,但没有 Page 2 具有的脚本标签。

这是第 1 页中的代码

<script>
jQuery(document).ready(function() {

    //jQuery('#navigation li a').click(function(){
    jQuery('#navigation li').on('click', 'a', function(){

    var toLoad = jQuery(this).attr('href')+' #global_content';
    jQuery('#global_content').fadeOut('fast',loadContent);
    jQuery('#load').remove();
    jQuery('#wrapper').append('<span id="load">LOADING...</span>');
    jQuery('#load').fadeIn('normal');
    function loadContent() {
        jQuery('#global_content').load(toLoad, function() {
        jQuery('#global_content').fadeIn('fast', hideLoader());

        });
    }
    function showNewContent() {
        jQuery('#global_content').show('normal',hideLoader());
    }
    function hideLoader() {
        jQuery('#load').fadeOut('normal');
    }
    return false;

    });
}); </script>

这是第 2 页中的代码

<div id="wall-feed-scripts">

  <script type="text/javascript">

    Wall.runonce.add(function () {

      var feed = new Wall.Feed({
        feed_uid: 'wall_91007',
        enableComposer: 1,
        url_wall: '/widget/index/name/wall.feed',
        last_id: 38,
        subject_guid: '',
        fbpage_id: 0      });

      feed.params = {"mode":"recent","list_id":0,"type":""};

      feed.watcher = new Wall.UpdateHandler({
        baseUrl: en4.core.baseUrl,
        basePath: en4.core.basePath,
        identity: 4,
        delay: 30000,
        last_id: 38,
        subject_guid: '',
        feed_uid: 'wall_91007'
      });
      try {
        setTimeout(function () {
          feed.watcher.start();
        }, 1250);
      } catch (e) {
      }

    });

  </script>
</div>

<div class="wallFeed">
some content
</div>

但我得到的输出是

<div id="wall-feed-scripts"></div>

 <div class="wallFeed">
    some content
    </div>

你能帮忙吗?

【问题讨论】:

  • 这是设计使然,&lt;scripts&gt; 未加载/执行。
  • 你会想要使用$.getScript()
  • @JayBlanchard,但 getScripts() 意味着我必须将 js 脚本放在文件 .js 中
  • 所以?那有什么问题?你应该尽可能地分开你的代码。

标签: javascript jquery html jquery-load


【解决方案1】:

直接使用jquery.ajax可以绕过jQuery.load stripping &lt;script&gt; tags的限制,这是shorthand methodsloadgetpost等使用的底层方法。 我们将使用jquery.html(它使用innerHTML)来更新DOM。

var toLoad         = this.href,
    toLoadSelector = '#global_content';

...

function loadContent() {
    jQuery.ajax({
        url: toLoad,
        success: function(data,status,jqXHR) {
            data = jQuery(data).find( toLoadSelector );
            jQuery('#global_content').html(data).fadeIn('fast', hideLoader());
        }
    });
}

如您所见,我们在响应中应用选择器 toLoadSelector ('#global_content') 以仅插入页面的所需部分。

更新

更好的方法是在loadContent 函数中引入一些参数,使其更易于重用。这是一个更新(和测试)的版本:

<script>
jQuery(function($) {

    $('#navigation li a').on('click', function() {
        loadContent( '#global_content', this.href, '#global_content' );
        return false;
    });

    function loadContent(target, url, selector) {

        $(target).fadeOut('fast', function() {

            showLoader();

            $.ajax({
                url: url,
                success: function(data,status,jqXHR) {
                    $(target).html($(data).find(selector).addBack(selector).children())
                    .fadeIn('fast', hideLoader());
                }
            });

        });
    }

    function showLoader() {
        $('#load').remove();
        $('#wrapper').append('<span id="load">LOADING...</span>').fadeIn('normal');
    }

    function hideLoader() {
        $('#load').fadeOut('normal');
    }
});
</script>

关于更改的几点说明:

jQuery(function() { ... })

相同
jQuery(document).ready( function() { ... } )

指定function($) 使jQuery 在函数中可用作$,这样可以节省一些输入。

现在,关于这个表达式:

$(data).find(selector).addBack(selector).children()

不幸的是,$("&lt;div id='foo'&gt;").find('#foo') 不返回任何结果:只有后代匹配。这意味着如果 Page2&lt;body&gt; 下直接有#global_content div,它将不起作用。添加addBack(selector) 可以匹配顶级元素本身。详情请见this so question

.children() 确保 Page2 中的 &lt;div id='global_content'&gt; 标记本身不包含在内,否则 Page1 将包含

<div id="global_content">
    <div id="global_content">

这在技术上是非法的,因为 id 在文档中必须是唯一的。

【讨论】:

  • 此代码也会加载标题。是否可以只加载#global_content 内容?
  • 为什么 OP 应该“试试这个”? 好的答案将始终解释所做的事情以及这样做的原因,不仅适用于 OP,也适用于 SO 的未来访问者。
  • @Jay 你在哪里看到“试试这个”
  • @Alvin 什么意思,加载标题?这应该将 #global_content 的内容 (innerHTML) 替换为 toLoad url 返回的任何内容。
  • 你没有提供任何解释,所以这相当于“试试这个”的答案。
【解决方案2】:

我最近遇到了类似的问题。如 cmets 中所述,当通过 load() 加载内容时,jQuery 会忽略脚本标签。有人提到您应该使用$.getScript(),但这在严格模式下不起作用,因为通过getScript() 加载的内容是通过eval() 加载的,并且无法访问全局范围。所以getScript() 会破坏你的javascript。解决它的唯一方法是使用 vanilla javascript。

// $.getScript() uses eval() which makes it impossible to define functions in 
// the global namespace in strict mode. Hence the closure thing here...
(function (callback) {
    var script = document.createElement("script");
    script.setAttribute("src", "./app/js/sequences/autoloader.php");
    script.addEventListener('load', callback);
    document.body.appendChild(script);
})(function () {
    // Callback funtion here
});

【讨论】:

  • 感谢您的回复,但我不太清楚应该如何用自己的代码实现此代码。你能帮帮我吗?
猜你喜欢
  • 2012-12-29
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
相关资源
最近更新 更多