4

我的目的是,我想从数据中取出特定的 html 并仅更新该区域。

如何过滤从 jQuery.ajax 返回的数据?

该链接是旧帖子,但我确实遇到了完全相同的问题。

从链接给出的解决方案是$("[ref=B]").html(data).find( '[ref=A]' );

但是,如果我这样做,整个页面将<span ref='B'>首先写入,然后在其中找到选择器.....

仅找到 '[ref=A]' 的另一种方法是

html = $(data).filter('[ref=B]').find('[ref=A]').html() // this way will work

这些都不行

$(data).find('[ref=A]').html();
$(data).filter('[ref=A]').html();
$(data).filter('body').html();
$(data).find('body').html();

HTML

`<body>

<span ref='B'><span ref='A'>abc</span></span>

</body>`

JS

 $(function() {
$.get(window.location.pathname + window.location.search, function(data){ alert(data);});
 });

返回数据

<html>
<body>
    <span ref='B'><span ref='A'>abc</span></span>
</body>
</html>

我的问题是,有没有一种解决方案可以从 $.ajax 返回的数据中过滤 body 的 html?像

body_html = $(data).??????? 

然后我可以做任何我想做的事,比如

body_html.find('xxxx');

非常感谢您的建议。

4

2 回答 2

3

您可以使用DocumentFragment来模拟您的 html 并在不将其附加到DOM的情况下进行搜索。

// Create your DocumentFragment to be able to work without DOM
var body_html = document.createDocumentFragment();

// Convert and append data from your jQuery to work with fragment
body_html.appendChild($(data)[0]);

// Now you can select using your jQuery
var $body_html = $(body_html);

// Now you can use the find or whatever you want, like if it was in the DOM
$body_html.find('.foo');

// Or you can append in your current document, 
// but attention, after it the fragment reference is erased
$body_html.appendTo(document.body); 
// now you need to get reference again from body, 
// because your fragment doesn't exists anymore.

// So... if you try:
console.log(body_html); // undefined
console.log($body_html); // jquery over undefined, probably just a jquery useless

// At this point you will need to reference from DOM to continue manipulation
$body_html = $(document.body);
// Now I'm ready to continue the work
// This var is like your DocumentFragment, but already on DOM.

您也可以在 jQuery 模板中进行过滤,$(data).filter('.foo')但正如您在此测试中看到的那样,您的性能会下降很多。

于 2013-01-08T00:38:41.017 回答
2
$("[ref=B]").append($(data).find("[ref=A]"));

你在你的问题中这样做的方式,最后一部分find( '[ref=A]' )是没用的。

[编辑]另外,另一个问题已经超过2年了。对于最新版本的 jQuery,您可能需要额外的引号:

$("[ref='B']").append($(data).find("[ref='A']"));
于 2013-01-08T01:01:07.477 回答