Jquery load() 不加载 div 中的脚本标签

Jquery load() doesn't load script tags in div

第 1 页 有一个 ID 为 (#navigation) 的菜单,一个名为 Page2 的 link 和 ID 为 (global_content 的 DIV ) 在单击 link Page2 时显示内容。在同一页(第 1 页)中,我写了一个 jquery 加载函数,这样当我单击 link 时,它应该显示内容而无需重新加载页面。加载事件工作正常,显示了内容,但没有 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>

你能帮忙吗?

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

可以绕过jQuery.load stripping <script> tags by using jquery.ajax directly, which is the underlying method used for the 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()

不幸的是,$("<div id='foo'>").find('#foo') 没有 return 任何结果:只有后代匹配。也就是说如果Page2#global_contentdiv直接在<body>下面,就不行了。添加 addBack(selector) makes it possible to match the top-level element itself. See this so question 以获取更多详细信息。

.children() 确保 Page2 中的 <div id='global_content'> 标签本身不包含在内,否则 Page1会有

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

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