javascript - ajax加载的html片段js代码不执行?
PHP中文网
PHP中文网 2017-04-11 12:16:22
[JavaScript讨论组]
export function init(){
     
    window.onhashchange = function(){
        var hash = location.hash;
        hash = hash.substring(1,hash.length);
        loadHtmlData(hash);
        console.log(hash)
    }
     
     

}


export function loadHtmlData(page){
    $.ajax({
        url:page + '.html',
        dataType:'html',
        success:function(data){
            $('#ajaxContainer').html('').append(data);
        }
    })
}

hash改变的时候,发起请求去加载页面,但是加载的页面的js并不执行?请问下这是为什么?

PHP中文网
PHP中文网

认证0级讲师

全部回复(2)
阿神

因为HTML和js代码是append进去的,等append进去HTML后再执行需要执行的js

天蓬老师

$? 用的jQuery?。我扣了一段jQuery代码:

// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
    if ( typeof data !== "string" ) {
        return [];
    }
    if ( typeof context === "boolean" ) {
        keepScripts = context;
        context = false;
    }
    var base, parsed, scripts;
    if ( !context ) {
        // Stop scripts or inline event handlers from being executed immediately
        // by using document.implementation
        if ( support.createHTMLDocument ) {
            context = document.implementation.createHTMLDocument( "" );
            // Set the base href for the created document
            // so any parsed elements with URLs
            // are based on the document's URL (gh-2965)
            base = context.createElement( "base" );
            base.href = document.location.href;
            context.head.appendChild( base );
        } else {
            context = document;
        }
    }
    parsed = rsingleTag.exec( data );
    scripts = !keepScripts && [];
    // Single tag
    if ( parsed ) {
        return [ context.createElement( parsed[ 1 ] ) ];
    }
    parsed = buildFragment( [ data ], context, scripts );
    if ( scripts && scripts.length ) {
        jQuery( scripts ).remove();
    }
    return jQuery.merge( [], parsed.childNodes );
};

jQuery在把string转化为HTML时,默认是会去除script标签的。 所以,没有执行JS脚本

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号