html不加载页面直接执行代码,ajax加载的html片段js代码不执行?

这篇博客探讨了jQuery的parseHTML函数在将HTML字符串转换为DOM元素时,如何默认移除script标签以防止立即执行JavaScript脚本。文章详细解释了函数的工作原理,包括创建上下文、处理单标签以及如何处理脚本元素。同时,提到了可以通过设置参数来控制是否保留脚本。
摘要由CSDN通过智能技术生成

$? 用的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脚本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值