简体   繁体   中英

Use jQuery with my own document object

I'm making a greasemonkey userscript that is supposed to preload certain data (actually, xkcd comic strips) and display them when link is clicked.

My task mostly consists of retrieving data from DOM fetched by ajax and assigning the values to DOM the user is viewing. This is one particular case I find jQuery incredibly helpful. But jQuery operates on window.document .

I load and parse document like this :

   xhr.onload = function() {
       var doc = document.implementation.createDocument(
         'http://www.w3.org/1999/xhtml',
         'html',
         document.doctype
       );
       doc.documentElement.innerHTML = this.responseText;
   }

And I need to perform jQuery selectors on doc , so that I can retrieve the site data (such as comic title).

Once more, the question: How to perform jQuery selectors on custom document object?

You can simply use $(doc) and jQuery's traversal methods:

var $doc = $(doc);

var comicContainer = $doc.find('#comics'); // for example

例如,要将单击事件添加到自定义加载的项目中,请使用以下命令:

$(body).on( 'click', 'YOUR_DYNAMIC_SELECTOR', function(){ DO_ALL_THIS } )

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