开发者

Extracting a script

开发者 https://www.devze.com 2023-03-15 20:54 出处:网络
I have a DIV I want to ajax-load.The contains javascript that needs to run.I ran across this SO article that talks about loading the scripts after the main content has loaded.However I cannot get it t

I have a DIV I want to ajax-load. The contains javascript that needs to run. I ran across this SO article that talks about loading the scripts after the main content has loaded. However I cannot get it to work, primarily because I can't fin开发者_开发问答d the scripts in my content!

Consider the following:

$('<p />').html('<div>x</div>').find('div').html()
"x"

(for some reason the line below wouldn't work:

$('<p><div>x</div></p>').find('div').html()
null

However, there's something special about scripts:

$('<p />').html('<script>x=1</script>').find('script').html()
null

what am I doing wrong here?


Script tags get scrapped from jQuery .html()


Neal is right. I'd recommend adding the script tag with plain JS:

var scriptTag = document.createElement('script');
script.text = 'alert("testing");';
// if you're linking to a remote script, use script.src instead

document.getElementById('parentID').appendChild(script);
// to append to the body, use document.body.appendChild
0

精彩评论

暂无评论...
验证码 换一张
取 消