简体   繁体   中英

Using JQuery with a string (instead of DOM)

I remember using a plugin in the past where I could use AJax to load a page and update only part of the DOM. The AJax request returns the entire HTML page, but only a small portion of it replaces part of the currently loaded DOM.

For example, SO can use this function to fetch http://stackoverflow.com and only update #content . SO would make an AJax request to fetch http://stackoverflow.com , fetch #content from the returned string, and update #content of the DOM.

Sorry if my question is confusing. How would I do this without a plugin?

The .load() function is designed to do this. Just include a selector for an element along with the URL, like so:

$('#content').load('http://stackoverflow.com #content', optionalCallbackFunction);

That will replace the content of the element with ID content on the current page, with the contents of the element with ID content on the page returned by an AJAX request to http://stackoverflow.com , then run the function called optionalCallbackFunction . Assuming, of course, that the request was successful.

Without the AJAX, you can parse a raw string like this:

var str = "<div><h1>Page Title</h1><div id='content'>This is new.</div></div>";
var text = $("#content",$(str)).html();
$('#content').html(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM