Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - jquery: Keep <script> tag after .find()

I'm trying to add ajax to WordPress by jquery-ajaxy plugin, and I'm stuck with one thing:

My page is loaded by ajax call, filtered, and appended to dom. So in short, it would be:

data = this.state.Response.data; //full html of page returned by ajax
$mainContent = $(data).find("#content"); //we filter out what we need 
$('#content_div').append($mainContent); //we display it

Easy for now, but there are inline js scripts in $mainContent, which are striped by jquery. I need them, somehow.

It all works, if I just do

.append(data);  

But data contains full html (doctype, head, meta) which I can't append. So, is there a way to make those tags work after .find()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Whenever you create a jQuery object from a string, script tags are automatically stripped. You can see a discussion in here: JavaScript RegEx for div tags

What I would do, as suggested in a post in the thread above, is to wrap the content in special comment tags and use javascript match() to extract it, the append the whole string.

data = this.state.Response.data; //full html of page returned by ajax

//Assuming your data looks like: ...<!--Content Start-->CONTENT<!--Content End-->...
//we filter out what we need 
data = data.match(/<!--Content Start-->(.*?)<!--Content End-->/)[1];

$('#content_div').append(data); //we display it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...