提取jQuery的HTML文档的一部分 [英] Extract part of HTML document in jQuery

查看:99
本文介绍了提取jQuery的HTML文档的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打一个AJAX调用到HTML返回页面中,提取HTML的一部分(使用jQuery选择器),然后使用该部分在我的基于jQuery JavaScript的。

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.

借助 AJAX检索是pretty的简单。这给了我整个HTML文档中的回调函数的数据参数。

The AJAX retrieval is pretty simple. This gives me the entire HTML document in the "data" parameter of the callback function.

我不明白的是如何处理数据的有效方法。我想它包装在一个新的jQuery对象,然后使用一个选择(通过查找()我相信)得到的只是我想要的一部分。一旦我有,我会其传递到另一个JavaScript对象插入到我的文件。 (这个代表团就是为什么我没有在第一时间使用jQuery.load())。

What I don't understand is how to handle that data in a useful way. I'd like to wrap it in a new jQuery object and then use a selector (via find() I believe) to get just the part I want. Once I have that I'll be passing it off to another JavaScript object for insertion into my document. (This delegation is why I'm not using jQuery.load() in the first place).

的get()的例子我看到的好像都是这个变化:

The get() examples I see all seem to be variations on this:

$('.result').html(data);

......,如果我理解正确的话,插入的全部的文档返回到选定的元素。这不仅是可疑的(没有此插入< HEAD> 等)。但它太粗了我想要的

...which, if I understand it correctly, inserts the entire returned document into the selected element. Not only is that suspicious (doesn't this insert the <head> etc?) but it's too coarse for what I want.

在替代方式建议要做到这一点是最欢迎的。

Suggestions on alternate ways to do this are most welcome.

推荐答案

您可以使用标准的选择器语法,并通过了数据的上下文选择。第二个参数,在这种情况下,数据,是我们的环境。

You can use your standard selector syntax, and pass in the data as the context for the selector. The second parameter, data in this case, is our context.

$.post("getstuff.php", function(data){
  var mainDiv = $("#mainDiv", data); // finds <div id='mainDiv'>...</div>
}, "html");

这相当于做:

$(data).find("#mainDiv");

根据您打算使用此, $。负载()可能是一个更好的途径来取,因为它同时允许一个URL和一个选择器过滤所得到的数据,将其直接传递到方法被称为在元件:

Depending on how you're planning on using this, $.load() may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:

$("#mylocaldiv").load("getstuff.php #mainDiv");

这将加载&LT的内容; DIV ID ='mainDiv'&GT; ...&LT; / DIV&GT; getstuff.php 到我们本地的页面元素&LT; D​​IV ID ='mylocaldiv'&GT; ...&LT; / DIV&GT;

This would load the contents of <div id='mainDiv'>...</div> in getstuff.php into our local page element <div id='mylocaldiv'>...</div>.

这篇关于提取jQuery的HTML文档的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆