ajax加载的html片段js代码不执行?

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并不执行?请问下这是为什么?

阅读 5.2k
3 个回答

因为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脚本

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题